示例#1
0
文件: ssh.py 项目: jos666/batch_ssh
 def login(self, ip, user, passwd, port=22, key=None, key_pass=None):
     'login to ssh server'
     self.set_missing_host_key_policy(AutoAddPolicy())
     if key:
         try:
             key_file = RSAKey.from_private_key_file(key)
         except PasswordRequiredException:
             key_file = RSAKey.from_private_key_file(key, key_pass)
     else:
         key_file = None
     try:
         self.connect(ip, port, user, passwd, pkey=key_file)
         self.login_status = True
     except AuthenticationException:
         print "Error: user or password error, info: ", \
             "ip:", ip, self.error_get()[1]
         self.login_status = False
     except socket.error:
         print "Error: do't connect to host: %s, info: %s " % \
             (ip, str(self.error_get()[1]))
         self.login_status = False
     except Exception:
         self.login_status = False
         print "Error: host: %s unknow errow, info: %s" % (
             ip, str(self.error_get()[1]))
示例#2
0
 def _ssh_connect(self, key_file: Path):
     print(f"Connecting to {self.user}@{self.server}:{self.port} ...")
     self.ssh = SSHClient()
     self.ssh.load_host_keys(
         os.path.expanduser(os.path.join('~', '.ssh', 'known_hosts')))
     self.ssh.set_missing_host_key_policy(AutoAddPolicy())
     try:
         key = RSAKey.from_private_key_file(key_file.as_posix())
     except PasswordRequiredException:
         ssh_pass = getpass.getpass(f"Password for {key_file.as_posix()}: ")
         key = RSAKey.from_private_key_file(key_file.as_posix(), ssh_pass)
     self.ssh.connect(self.server, self.port, self.user, pkey=key)
示例#3
0
 def test_bad_hostkey(self):
     badkey = RSAKey.from_private_key_file(_support('test_rsa.key'))
     public_badkey = RSAKey(data=badkey.asbytes())
     host_key = RSAKey.from_private_key_file(_support('test_rsa_2k_o.key'),
                                             password='******')
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.ts.start_server(event, server)
     self.assertRaises(
         BadHostKeyException, self.tc.connect,
         hostkey=public_badkey, username='******', password='******'
     )
示例#4
0
 def _check_keypair_from_file(self, ref_fingerprint, private_key_path):
     """Function to check if a certain keypair from a file matches the fingerprint
     from a reference one
     :param str ref_fingerprint: fingerprint to be compared
     :raises: KeypairError: if the keypair is not valid, or if the fingerprint to check
                         and the one computed from the private key is not the same
     :raises: KeyNotAccessible: if the private key is password protected
                         and the password provided is not correct
     """
     
     pkey=None
     
     # This block avoid repetition of checks after it is done for the first instance
     if self._SSH_KEY_CHECKED==True:
         if self._SSH_KEY_ACCESS_ERROR==True: # This avoid user entering the code right the second time
             raise KeyNotAccessible#("Unable to access key file `"+private_key_path+": Invalid password")  
         else:
             return
     try:
         pkey=DSSKey.from_private_key_file(private_key_path)
     except PasswordRequiredException:
         try:
             asked_password = getpass.getpass('Enter passphrase for '+private_key_path+ ':')
             pkey=DSSKey.from_private_key_file(private_key_path,asked_password)
         except SSHException:
             self._SSH_KEY_CHECKED=True
             self._SSH_KEY_ACCESS_ERROR=True # This avoid user entering the code right the second time
             raise KeyNotAccessible#("Unable to access key file `"+private_key_path+": Invalid password")      
     except SSHException:
         try:
             pkey=RSAKey.from_private_key_file(private_key_path)
         except PasswordRequiredException:
             try:
                 asked_password = getpass.getpass('Enter passphrase for '+private_key_path+ ':')
                 pkey=RSAKey.from_private_key_file(private_key_path,asked_password)
             except SSHException:
                 self._SSH_KEY_CHECKED=True
                 self._SSH_KEY_ACCESS_ERROR=True # This avoid user entering the code right the second time
                 raise KeyNotAccessible#("Unable to access key file `"+private_key_path+": Invalid password")  
         except SSHException:
             raise KeypairError('File `%s` is neither a valid DSA key '
                                'or RSA key' % private_key_path)
     fingerprint = str.join(
             ':', (i.encode('hex') for i in pkey.get_fingerprint()))
     if ref_fingerprint!=fingerprint:
         raise KeypairError(
             "Keypair from "+private_key_path+" is present but has "
             "different fingerprint. Aborting!")
     self._SSH_KEY_CHECKED=True
     return
示例#5
0
def check_ssh(ip, port, user, private_key):
    try:
        cli = client.SSHClient()
        cli.load_host_keys("/dev/null")
        cli.set_missing_host_key_policy(client.AutoAddPolicy())
        if private_key and user:
            print("[DEBUG-SSH] Trying pubkey auth for", ip)
            k = RSAKey.from_private_key_file(path + "checkfiles/" +
                                             private_key)
            cli.connect(ip,
                        port,
                        user,
                        banner_timeout=20,
                        timeout=20,
                        auth_timeout=20,
                        pkey=k)
        else:
            cli.connect(ip,
                        port,
                        "root",
                        "Password3#",
                        banner_timeout=20,
                        timeout=20,
                        auth_timeout=20)
        cli.close()
        return 1, None
    except Exception as e:
        if str(e) == "Authentication failed." and not private_key:
            return 1, None
        return 0, str(e)
示例#6
0
def push_war(war_location,
             target_address,
             purpose_directory,
             user='******',
             key_location='/root/.ssh/id_rsa'):
    """
    this is a function of translation .war file through scp and paramiko.
    """
    private_key = RSAKey.from_private_key_file(key_location)
    if not war_location[-4:] == '.war':
        return None

    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(AutoAddPolicy())

    try:
        ssh.connect(hostname=target_address, username=user, pkey=private_key)
        # scp use the ssh session
        scp = SCPClient(ssh.get_transport())
    except Exception as e:
        ssh.close()
        raise e
    else:
        scp.put(war_location, purpose_directory)
        scp.close()
        ssh.close()
        return True
示例#7
0
    def test_certificates(self):
        # NOTE: we also test 'live' use of cert auth for all key types in
        # test_client.py; this and nearby cert tests are more about the gritty
        # details.
        # PKey.load_certificate
        key_path = _support(os.path.join('cert_support', 'test_rsa.key'))
        key = RSAKey.from_private_key_file(key_path)
        self.assertTrue(key.public_blob is None)
        cert_path = _support(
            os.path.join('cert_support', 'test_rsa.key-cert.pub')
        )
        key.load_certificate(cert_path)
        self.assertTrue(key.public_blob is not None)
        self.assertEqual(key.public_blob.key_type, '*****@*****.**')
        self.assertEqual(key.public_blob.comment, 'test_rsa.key.pub')
        # Delve into blob contents, for test purposes
        msg = Message(key.public_blob.key_blob)
        self.assertEqual(msg.get_text(), '*****@*****.**')
        nonce = msg.get_string()
        e = msg.get_mpint()
        n = msg.get_mpint()
        self.assertEqual(e, key.public_numbers.e)
        self.assertEqual(n, key.public_numbers.n)
        # Serial number
        self.assertEqual(msg.get_int64(), 1234)

        # Prevented from loading certificate that doesn't match
        key_path = _support(os.path.join('cert_support', 'test_ed25519.key'))
        key1 = Ed25519Key.from_private_key_file(key_path)
        self.assertRaises(
            ValueError,
            key1.load_certificate,
            _support('test_rsa.key-cert.pub'),
        )
示例#8
0
def get(nodes_file, request):
    """Return the logs"""
    args = dict(request.args.items())
    try:
        container = args.pop('container')
    except KeyError:
        raise errors.BadRequest('No container on URL arguments')
    results = dict()

    with open(nodes_file) as f:
        nodes = yaml.load(f)
        try:
            rsa_key_file = nodes.pop('rsa_key')
            pkey = RSAKey.from_private_key_file(rsa_key_file)
        except Exception as e:
            print('Failed to read RSA Key, {} {}'.format(type(e), e))
            raise
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy)
        cmd = 'docker logs {container} {args}'.format(
            container=container,
            args=' '.join(['--{}={}'.format(a, args[a]) for a in args]))

        for _, ips in nodes.items():
            for ip in ips:
                ssh.connect(hostname=ip, username='******', pkey=pkey)
                print('ssh root@{ip} {cmd}'.format(ip=ip, cmd=cmd))
                _in, _out, _err = ssh.exec_command(cmd)
                status = _out.channel.recv_exit_status()
                results[ip] = dict(status=status,
                                   stdout=_out.read(),
                                   stderr=_err.read())
        ssh.close()
    return results
示例#9
0
    def test_H_compression(self):
        """
        verify that zlib compression is basically working.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)
        self.ts.get_security_options().compression = ('zlib',)
        self.tc.get_security_options().compression = ('zlib',)
        event = threading.Event()
        server = NullServer()
        self.ts.start_server(event, server)
        self.tc.connect(hostkey=public_host_key,
                        username='******', password='******')
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())

        chan = self.tc.open_session()
        chan.exec_command('yes')
        schan = self.ts.accept(1.0)

        bytes = self.tc.packetizer._Packetizer__sent_bytes
        chan.send('x' * 1024)
        bytes2 = self.tc.packetizer._Packetizer__sent_bytes
        # tests show this is actually compressed to *52 bytes*!  including packet overhead!  nice!! :)
        self.assert_(bytes2 - bytes < 1024)
        self.assertEquals(52, bytes2 - bytes)

        chan.close()
        schan.close()
示例#10
0
    def test_9_interactive_auth(self):
        """
        verify keyboard-interactive auth works.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assert_(not event.isSet())
        self.ts.start_server(event, server)
        self.tc.ultra_debug = True
        self.tc.connect(hostkey=public_host_key)

        def handler(title, instructions, prompts):
            self.got_title = title
            self.got_instructions = instructions
            self.got_prompts = prompts
            return ['cat']
        remain = self.tc.auth_interactive('commie', handler)
        self.assertEquals(self.got_title, 'password')
        self.assertEquals(self.got_prompts, [('Password', False)])
        self.assertEquals([], remain)
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())
示例#11
0
 def test_4_special(self):
     """
     verify that the client can demand odd handshake settings, and can
     renegotiate keys in mid-stream.
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.ts.start_server(event, server)
     options = self.tc.get_security_options()
     options.ciphers = ('aes256-cbc',)
     options.digests = ('hmac-md5-96',)
     self.tc.connect(hostkey=public_host_key,
                     username='******', password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
     self.assertEquals('aes256-cbc', self.tc.local_cipher)
     self.assertEquals('aes256-cbc', self.tc.remote_cipher)
     self.assertEquals(12, self.tc.packetizer.get_mac_size_out())
     self.assertEquals(12, self.tc.packetizer.get_mac_size_in())
     
     self.tc.send_ignore(1024)
     self.tc.renegotiate_keys()
     self.ts.send_ignore(1024)
示例#12
0
def create_library():
    pkey_filename = '/Users/cole/.ssh/million-song-dataset.pem'
    pkey_password = keyring.get_password('SSH', pkey_filename)
    pkey = RSAKey.from_private_key_file(pkey_filename, password=pkey_password)
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect('52.91.85.148', username='******', pkey=pkey)

    letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
               'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    letters2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    letters3 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

    dr = DataReader()
    dr.reset_lib()
    import shutil
    for letter in letters:
        for letter2 in letters2:
            for letter3 in letters3:
                with SCPClient(ssh.get_transport()) as scp:
                    print letter + letter2 + letter3
                    scp.get('/mnt/snap/data/' + letter + '/' + letter2 + '/' + letter3,
                            '/Users/cole/eclipse-workspace/EC2 File Transfer/Data/', 1)
                    dr.append_files(letter3);
                    shutil.rmtree('/Users/cole/eclipse-workspace/EC2 File Transfer/Data/' + letter3);
                    scp.close()
    ssh.close()
示例#13
0
    def __init__(self, host, port, tun_host, tun_port, tun_user, tun_password,
                 pkey_path, pkey_password):
        self.host = host
        self.port = int(port)
        self.tun_host = tun_host
        self.tun_port = int(tun_port)
        self.tun_user = tun_user
        self.tun_password = tun_password

        if pkey_path:
            self.private_key = RSAKey.from_private_key_file(
                pkey_path, password=pkey_password)
            self.server = SSHTunnelForwarder(
                ssh_address_or_host=(self.tun_host, self.tun_port),
                ssh_username=self.tun_user,
                ssh_pkey=self.private_key,
                remote_bind_address=(self.host, self.port),
            )
        else:
            self.server = SSHTunnelForwarder(
                ssh_address_or_host=(self.tun_host, self.tun_port),
                ssh_username=self.tun_user,
                ssh_password=self.tun_password,
                remote_bind_address=(self.host, self.port),
            )
        self.server.start()
示例#14
0
    def test_H_compression(self):
        """
        verify that zlib compression is basically working.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)
        self.ts.get_security_options().compression = ('zlib', )
        self.tc.get_security_options().compression = ('zlib', )
        event = threading.Event()
        server = NullServer()
        self.ts.start_server(event, server)
        self.tc.connect(hostkey=public_host_key,
                        username='******',
                        password='******')
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())

        chan = self.tc.open_session()
        chan.exec_command('yes')
        schan = self.ts.accept(1.0)

        bytes = self.tc.packetizer._Packetizer__sent_bytes
        chan.send('x' * 1024)
        bytes2 = self.tc.packetizer._Packetizer__sent_bytes
        # tests show this is actually compressed to *52 bytes*!  including packet overhead!  nice!! :)
        self.assert_(bytes2 - bytes < 1024)
        self.assertEquals(52, bytes2 - bytes)

        chan.close()
        schan.close()
示例#15
0
    def test_9_interactive_auth(self):
        """
        verify keyboard-interactive auth works.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assert_(not event.isSet())
        self.ts.start_server(event, server)
        self.tc.ultra_debug = True
        self.tc.connect(hostkey=public_host_key)

        def handler(title, instructions, prompts):
            self.got_title = title
            self.got_instructions = instructions
            self.got_prompts = prompts
            return ['cat']

        remain = self.tc.auth_interactive('commie', handler)
        self.assertEquals(self.got_title, 'password')
        self.assertEquals(self.got_prompts, [('Password', False)])
        self.assertEquals([], remain)
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())
示例#16
0
    def test_4_special(self):
        """
        verify that the client can demand odd handshake settings, and can
        renegotiate keys in mid-stream.
        """
        host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = RSAKey(data=str(host_key))
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assert_(not event.isSet())
        self.ts.start_server(event, server)
        options = self.tc.get_security_options()
        options.ciphers = ('aes256-cbc', )
        options.digests = ('hmac-md5-96', )
        self.tc.connect(hostkey=public_host_key,
                        username='******',
                        password='******')
        event.wait(1.0)
        self.assert_(event.isSet())
        self.assert_(self.ts.is_active())
        self.assertEquals('aes256-cbc', self.tc.local_cipher)
        self.assertEquals('aes256-cbc', self.tc.remote_cipher)
        self.assertEquals(12, self.tc.packetizer.get_mac_size_out())
        self.assertEquals(12, self.tc.packetizer.get_mac_size_in())

        self.tc.send_ignore(1024)
        self.tc.renegotiate_keys()
        self.ts.send_ignore(1024)
示例#17
0
文件: command.py 项目: ijidan/jdeploy
	def connectRemoteAddress(self,remote_user,remote_address,key_file):
		ssh=SSHClient()
		ssh.load_system_host_keys()
		private_key=path.expanduser("~/.ssh/id_rsa")
		key=RSAKey.from_private_key_file(private_key)
		ssh.connect(username=remote_user,hostname=remote_address,pkey=key)
		return ssh
示例#18
0
 def test_3_simple(self):
     """
     verify that we can establish an ssh link with ourselves across the
     loopback sockets.  this is hardly "simple" but it's simpler than the
     later tests. :)
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=bytes(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.assertEquals(None, self.tc.get_username())
     self.assertEquals(None, self.ts.get_username())
     self.assertEquals(False, self.tc.is_authenticated())
     self.assertEquals(False, self.ts.is_authenticated())
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******', password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
     self.assertEquals('slowdive', self.tc.get_username())
     self.assertEquals('slowdive', self.ts.get_username())
     self.assertEquals(True, self.tc.is_authenticated())
     self.assertEquals(True, self.ts.is_authenticated())
示例#19
0
    def _push_smtppasswd_file(self):
        logger.info('Pushing smtppasswd file for %s', self)

        # do this early in order not to fail while connected
        contents = self.get_smtppasswd_file_contents()

        pkey = RSAKey.from_private_key_file(
            settings.KOMPASSI_SSH_PRIVATE_KEY_FILE)

        with SSHClient() as client:
            client.load_host_keys(settings.KOMPASSI_SSH_KNOWN_HOSTS_FILE)
            client.connect(
                hostname=self.ssh_server,
                port=self.ssh_port,
                username=self.ssh_username,
                pkey=pkey,
            )

            with client.open_sftp() as sftp_client:
                with sftp_client.file(self.password_file_path_on_server,
                                      'w') as output_file:
                    output_file.write(contents.encode('UTF-8'))

                with sftp_client.file(self.trigger_file_path_on_server,
                                      'w') as trigger_file:
                    pass

        logger.info('Successfully pushed smtppasswd file for %s', self)
示例#20
0
def fileChooser(returnv=False):
    """Need both the chooser list with values showing all files selected to start with
    something like [
                {'label': 'New York City', 'value': 'NYC'},
                {'label': 'Montreal', 'value': 'MTL'},
                {'label': 'San Francisco', 'value': 'SF'}
            ]
    """
    upload_remote_path = BaseConfig.REMOTEDATAPATH
    sftpkey = RSAKey.from_private_key_file(BaseConfig.SFTPKEYFILENAME)
    sftp = SftpClient(BaseConfig.REMOTEDATAHOST, BaseConfig.SFTPPORT,
                      BaseConfig.SFTPLOGINUSER, BaseConfig.SFTPPASSWORD,
                      sftpkey)
    sftp.dirch(upload_remote_path)
    fl = sftp.dirlist(upload_remote_path)
    fl.sort()
    fl = [x for x in fl if (x.split('.')[-1] == 'xls')]
    ddl = []
    vals = []
    for fn in fl:
        ddl.append({'label': os.path.split(fn)[-1], 'value': fn})
        vals.append(fn)
    if returnv:
        return vals
    else:
        return ddl
示例#21
0
 def establish_connection(self):
     config.logging_result.append_text(
         self._self,
         "Establishing ssh connection with {0}".format(self.srv_addr))
     config.ssh_array[self.srv_addr] = SSHClient()
     config.ssh_array[self.srv_addr].set_missing_host_key_policy(
         AutoAddPolicy())
     # TODO Handle with ssh auth exceptions
     # Key auth type
     if self.config[self.srv_addr].getboolean("auth_type_key"):
         key = RSAKey.from_private_key_file(
             self.config[self.srv_addr]["key_path"])
         config.ssh_array[self.srv_addr].connect(
             self.srv_addr,
             port=self.config[self.srv_addr]["auth_ssh_port"],
             username=self.config[self.srv_addr]["auth_username"],
             pkey=key)
     # Password auth type
     elif self.config[self.srv_addr].getboolean("auth_type_password"):
         config.ssh_array[self.srv_addr].connect(
             self.srv_addr,
             port=self.config[self.srv_addr]["auth_ssh_port"],
             username=self.config[self.srv_addr]["auth_username"],
             password=self.config[self.srv_addr]["auth_password"])
     config.logging_result.append_text(
         self._self,
         "Connection with {0} established".format(self.srv_addr),
         success=True)
     # Setting connection completion flag
     self.ready.set()
示例#22
0
def ssh_wrapper(cmd, host=None):
    debug("ssh_wrapper(%s)" % cmd)
    if not host:
        host = current_app.config["SSH_SERVER"]
    login = current_app.config["SSH_USERNAME"]
    key_file = current_app.config["SSH_KEY"]
    key = RSAKey.from_private_key_file(key_file)
    timeout = current_app.config.get("SSH_TIMEOUT", 60)

    debug("Connecting to %s with login %s and key %s" %
          (host, login, key_file))
    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    try:
        client.connect(host, username=login, pkey=key, timeout=timeout)
    except AuthenticationException:
        error("Failed to connect to %s under using %s with key '%s'" %
              (host, login, key_file))
        client.close()
        return [], []
    except Exception as e:
        error(
            "Failed to establish a connection to %s due following error: %s" %
            (host, e))
        client.close()
        return [], []
    stdin, stdout, stderr = client.exec_command(cmd)
    output = stdout.readlines()
    errors = stderr.readlines()
    client.close()
    debug("Out: %s" % output)
    debug("Err: %s" % errors)
    return output, errors
示例#23
0
def trans():
    """
    Create `LoopSocket`-based server/client `Transport`s, yielding the latter.

    Uses `NullServer` under the hood.
    """
    # NOTE: based on the setup/teardown/start_server/verify_finished methods
    # found in ye olde test_auth.py

    # "Network" setup
    socks = LoopSocket()
    sockc = LoopSocket()
    sockc.link(socks)
    tc = Transport(sockc)
    ts = Transport(socks)

    # Start up the in-memory server
    host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
    ts.add_server_key(host_key)
    event = threading.Event()
    server = NullServer()
    ts.start_server(event, server)

    # Tests frequently need to call Transport.connect on the client side, etc
    yield tc

    # Close things down
    tc.close()
    ts.close()
    socks.close()
    sockc.close()
示例#24
0
def create_ssh_rsa_key_pair(passphrase, bits=2048):
  random_generator = Random.new().read
  keypair = RSA.generate(bits, random_generator)

  # extract keys
  privkey = keypair.exportKey('PEM', passphrase, pkcs=1)
  pubkey = '%s %s %s' % (keypair.publickey().exportKey("OpenSSH"), config.SSH_PRIV_KEY, str(datetime.now()))

  # writing keys to files
  priv_key_file = config.get_priv_ssh_key()
  pub_key_file = '%s.pub' % priv_key_file

  with open("%s" % priv_key_file, 'w', stat.S_IWUSR | stat.S_IRUSR) as f:
    f.write("%s" % privkey)
    f.close()
    os.chmod(priv_key_file, stat.S_IWUSR | stat.S_IRUSR)

  with open("%s" % pub_key_file, 'w') as f:
    f.write("%s" % pubkey)
    f.close()
  
  # Get fingerprint and encode it in format aa:bb:cc:dd:...
  fingerprint = RSAKey.from_private_key_file(priv_key_file, password=passphrase).get_fingerprint().encode('hex')
  fingerprint = ':'.join(fingerprint[i:i + 2] for i in xrange(0, len(fingerprint), 2))

  # If running under Windows, convert OpenSSH private key to PuTTY private key,
  # because pageant cannot load OpenSSH keys.
  if util.platform_is_windows():
    priv_key_file_putty = '%s.ppk' % priv_key_file
    cmd = '"%s" "%s" -e -o "%s"' % (util.get_path_to_exe('puttygencmd.exe'), priv_key_file, priv_key_file_putty)
    util.run(cmd)  
    os.remove(priv_key_file)
    os.rename(priv_key_file_putty, priv_key_file)

  return fingerprint
示例#25
0
    def from_file(filename, password = '', keytype = None):
        """
        Returns a new PrivateKey instance with the given attributes.
        If keytype is None, we attempt to automatically detect the type.

        @type  filename: string
        @param filename: The key file name.
        @type  password: string
        @param password: The key password.
        @type  keytype: string
        @param keytype: The key type.
        @rtype:  PrivateKey
        @return: The new key.
        """
        if keytype is None:
            try:
                key = RSAKey.from_private_key_file(filename)
                keytype = 'rsa'
            except SSHException, e:
                try:
                    key = DSSKey.from_private_key_file(filename)
                    keytype = 'dss'
                except SSHException, e:
                    msg = 'not a recognized private key: ' + repr(filename)
                    raise ValueError(msg)
示例#26
0
def sftp_server():
    """
    Set up an in-memory SFTP server thread. Yields the client Transport/socket.

    The resulting client Transport (along with all the server components) will
    be the same object throughout the test session; the `sftp` fixture then
    creates new higher level client objects wrapped around the client
    Transport, as necessary.
    """
    # Sockets & transports
    socks = LoopSocket()
    sockc = LoopSocket()
    sockc.link(socks)
    tc = Transport(sockc)
    ts = Transport(socks)
    # Auth
    host_key = RSAKey.from_private_key_file(_support("test_rsa.key"))
    ts.add_server_key(host_key)
    # Server setup
    event = threading.Event()
    server = StubServer()
    ts.set_subsystem_handler("sftp", SFTPServer, StubSFTPServer)
    ts.start_server(event, server)
    # Wait (so client has time to connect? Not sure. Old.)
    event.wait(1.0)
    # Make & yield connection.
    tc.connect(username="******", password="******")
    yield tc
示例#27
0
    def test_certificates(self):
        # PKey.load_certificate
        key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
        self.assertTrue(key.public_blob is None)
        key.load_certificate(test_path('test_rsa.key-cert.pub'))
        self.assertTrue(key.public_blob is not None)
        self.assertEqual(key.public_blob.key_type, '*****@*****.**')
        self.assertEqual(key.public_blob.comment, 'test_rsa.key.pub')
        # Delve into blob contents, for test purposes
        msg = Message(key.public_blob.key_blob)
        self.assertEqual(msg.get_text(), '*****@*****.**')
        nonce = msg.get_string()
        e = msg.get_mpint()
        n = msg.get_mpint()
        self.assertEqual(e, key.public_numbers.e)
        self.assertEqual(n, key.public_numbers.n)
        # Serial number
        self.assertEqual(msg.get_int64(), 1234)

        # Prevented from loading certificate that doesn't match
        key1 = Ed25519Key.from_private_key_file(test_path('test_ed25519.key'))
        self.assertRaises(
            ValueError,
            key1.load_certificate,
            test_path('test_rsa.key-cert.pub'),
        )
示例#28
0
    def from_file(filename, password='', keytype=None):
        """
        Returns a new PrivateKey instance with the given attributes.
        If keytype is None, we attempt to automatically detect the type.

        :type  filename: string
        :param filename: The key file name.
        :type  password: string
        :param password: The key password.
        :type  keytype: string
        :param keytype: The key type.
        :rtype:  PrivateKey
        :return: The new key.
        """
        if keytype is None:
            try:
                key = RSAKey.from_private_key_file(filename)
                keytype = 'rsa'
            except SSHException as e:
                try:
                    key = DSSKey.from_private_key_file(filename)
                    keytype = 'dss'
                except SSHException as e:
                    msg = 'not a recognized private key: ' + repr(filename)
                    raise ValueError(msg)
        key = PrivateKey(keytype)
        key.filename = filename
        key.password = password
        return key
示例#29
0
    def _set_authentication(self, password, private_key, private_key_pass):
        '''Authenticate the transport. prefer password if given'''
        if password is None:
            # Use Private Key.
            if not private_key:
                # Try to use default key.
                if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
                    private_key = '~/.ssh/id_rsa'
                elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
                    private_key = '~/.ssh/id_dsa'
                else:
                    raise CredentialException("No password or key specified.")

            if isinstance(private_key, (AgentKey, RSAKey)):
                # use the paramiko agent or rsa key
                self._tconnect['pkey'] = private_key
            else:
                # isn't a paramiko AgentKey or RSAKey, try to build a
                # key from what we assume is a path to a key
                private_key_file = os.path.expanduser(private_key)
                try:  # try rsa
                    self._tconnect['pkey'] = RSAKey.from_private_key_file(
                        private_key_file, private_key_pass)
                except paramiko.SSHException:  # if it fails, try dss
                    # pylint:disable=r0204
                    self._tconnect['pkey'] = DSSKey.from_private_key_file(
                        private_key_file, private_key_pass)
示例#30
0
    def test_L_handshake_timeout(self):
        """
        verify that we can get a hanshake timeout.
        """

        # Tweak client Transport instance's Packetizer instance so
        # its read_message() sleeps a bit. This helps prevent race conditions
        # where the client Transport's timeout timer thread doesn't even have
        # time to get scheduled before the main client thread finishes
        # handshaking with the server.
        # (Doing this on the server's transport *sounds* more 'correct' but
        # actually doesn't work nearly as well for whatever reason.)
        class SlowPacketizer(Packetizer):
            def read_message(self):
                time.sleep(1)
                return super(SlowPacketizer, self).read_message()

        # NOTE: prettttty sure since the replaced .packetizer Packetizer is now
        # no longer doing anything with its copy of the socket...everything'll
        # be fine. Even tho it's a bit squicky.
        self.tc.packetizer = SlowPacketizer(self.tc.sock)
        # Continue with regular test red tape.
        host_key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
        public_host_key = RSAKey(data=host_key.asbytes())
        self.ts.add_server_key(host_key)
        event = threading.Event()
        server = NullServer()
        self.assertTrue(not event.is_set())
        self.tc.handshake_timeout = 0.000000000001
        self.ts.start_server(event, server)
        self.assertRaises(EOFError,
                          self.tc.connect,
                          hostkey=public_host_key,
                          username='******',
                          password='******')
示例#31
0
def runSeg():
	evnts = getWCronlog(BaseConfig.CRONLOG)
	# print(evnts)	
	upload_remote_path = BaseConfig.REMOTEDATAPATH
	sftpkey = RSAKey.from_private_key_file(BaseConfig.SFTPKEYFILENAME)
	sftp = SftpClient(BaseConfig.REMOTEDATAHOST,BaseConfig.SFTPPORT,BaseConfig.SFTPLOGINUSER,BaseConfig.SFTPPASSWORD,sftpkey)
	sftp.dirch(BaseConfig.REMOTEDATAPATH)
	fl = sftp.dirlist(upload_remote_path)
	fl.sort()
	fl = [x for x in fl if (len(x.split('.')) > 1 and x.split('.')[1]=='xls')]
	if fl != None:
		lcd = loadCellDataMulti(BaseConfig.NSD,fl)
		datal = []
		for i, df in enumerate(lcd.dfs):
			nr = df.shape[0]
			print('###i=',i)
			if nr > 0:
				#segmints,segtab = segMentsLog(df,evnts)
				segmints,segtab = segMents(df,i)
				segments = ['\t'.join(x) for x in segmints]
				print(lcd.names[i],'segments=\n','\n'.join(segments))
				segtabs = ['\t'.join(x) for x in segtab]
				if i == 0:
					f = open(SEGTABFNAME,'w')
				else:
					f = open(SEGTABFNAME,'a')
				f.write(''.join(segtabs))
				f.close()
示例#32
0
    def setup_test_server(
        self, client_options=None, server_options=None, connect_kwargs=None,
    ):
        host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
        public_host_key = RSAKey(data=host_key.asbytes())
        self.ts.add_server_key(host_key)

        if client_options is not None:
            client_options(self.tc.get_security_options())
        if server_options is not None:
            server_options(self.ts.get_security_options())

        event = threading.Event()
        self.server = NullServer()
        self.assertTrue(not event.is_set())
        self.ts.start_server(event, self.server)
        if connect_kwargs is None:
            connect_kwargs = dict(
                hostkey=public_host_key,
                username='******',
                password='******',
            )
        self.tc.connect(**connect_kwargs)
        event.wait(1.0)
        self.assertTrue(event.is_set())
        self.assertTrue(self.ts.is_active())
示例#33
0
 def test_L_handshake_timeout(self):
     """
     verify that we can get a hanshake timeout.
     """
     # Tweak client Transport instance's Packetizer instance so
     # its read_message() sleeps a bit. This helps prevent race conditions
     # where the client Transport's timeout timer thread doesn't even have
     # time to get scheduled before the main client thread finishes
     # handshaking with the server.
     # (Doing this on the server's transport *sounds* more 'correct' but
     # actually doesn't work nearly as well for whatever reason.)
     class SlowPacketizer(Packetizer):
         def read_message(self):
             time.sleep(1)
             return super(SlowPacketizer, self).read_message()
     # NOTE: prettttty sure since the replaced .packetizer Packetizer is now
     # no longer doing anything with its copy of the socket...everything'll
     # be fine. Even tho it's a bit squicky.
     self.tc.packetizer = SlowPacketizer(self.tc.sock)
     # Continue with regular test red tape.
     host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
     public_host_key = RSAKey(data=host_key.asbytes())
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assertTrue(not event.is_set())
     self.tc.handshake_timeout = 0.000000000001
     self.ts.start_server(event, server)
     self.assertRaises(EOFError, self.tc.connect,
                       hostkey=public_host_key,
                       username='******',
                       password='******')
    def cmd(self, command="ls"):

        with open(self.access_keys_csv) as f:
            csv = f.readlines()

        conn = connect_to_region("eu-west-2",
                                 aws_access_key_id=csv[0].split('=')[1],
                                 aws_secret_access_key=csv[1].split('=')[1])

        def stringit(arr):
            arr2 = []
            for i in arr:
                i = i.decode("utf-8")
                arr2.append(i)
            return arr2

        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        privkey = RSAKey.from_private_key_file('scrapit.pem')
        ssh.connect(self.dns_name, username='******', pkey=privkey)

        stdin, stdout, stderr = ssh.exec_command(command)
        stdin.flush()
        data = stdout.read().splitlines()
        data = stringit(data)
        for line in data:
            print(line)

        ssh.close()

        return data
示例#35
0
def get(nodes_file, request):
    """Return the logs"""
    args = dict(request.args.items())
    try:
        container = args.pop('container')
    except KeyError:
        raise errors.BadRequest('No container on URL arguments')
    results = dict()

    with open(nodes_file) as f:
        nodes = yaml.load(f)
        try:
            rsa_key_file = nodes.pop('rsa_key')
            pkey = RSAKey.from_private_key_file(rsa_key_file)
        except Exception as e:
            print('Failed to read RSA Key, {} {}'.format(type(e), e))
            raise
        ssh = SSHClient()
        ssh.set_missing_host_key_policy(AutoAddPolicy)
        cmd = 'docker logs {container} {args}'.format(
            container=container,
            args=' '.join(['--{}={}'.format(a, args[a]) for a in args]))

        for _, ips in nodes.items():
            for ip in ips:
                ssh.connect(hostname=ip, username='******', pkey=pkey)
                print('ssh root@{ip} {cmd}'.format(ip=ip, cmd=cmd))
                _in, _out, _err = ssh.exec_command(cmd)
                status = _out.channel.recv_exit_status()
                results[ip] = dict(
                    status=status, stdout=_out.read(), stderr=_err.read())
        ssh.close()
    return results
示例#36
0
def sftp_server():
    """
    Set up an in-memory SFTP server thread. Yields the client Transport/socket.

    The resulting client Transport (along with all the server components) will
    be the same object throughout the test session; the `sftp` fixture then
    creates new higher level client objects wrapped around the client
    Transport, as necessary.
    """
    # Sockets & transports
    socks = LoopSocket()
    sockc = LoopSocket()
    sockc.link(socks)
    tc = Transport(sockc)
    ts = Transport(socks)
    # Auth
    host_key = RSAKey.from_private_key_file(_support('test_rsa.key'))
    ts.add_server_key(host_key)
    # Server setup
    event = threading.Event()
    server = StubServer()
    ts.set_subsystem_handler('sftp', SFTPServer, StubSFTPServer)
    ts.start_server(event, server)
    # Wait (so client has time to connect? Not sure. Old.)
    event.wait(1.0)
    # Make & yield connection.
    tc.connect(username='******', password='******')
    yield tc
示例#37
0
    def test_certificates(self):
        # NOTE: we also test 'live' use of cert auth for all key types in
        # test_client.py; this and nearby cert tests are more about the gritty
        # details.
        # PKey.load_certificate
        key_path = _support(os.path.join("cert_support", "test_rsa.key"))
        key = RSAKey.from_private_key_file(key_path)
        self.assertTrue(key.public_blob is None)
        cert_path = _support(
            os.path.join("cert_support", "test_rsa.key-cert.pub"))
        key.load_certificate(cert_path)
        self.assertTrue(key.public_blob is not None)
        self.assertEqual(key.public_blob.key_type,
                         "*****@*****.**")
        self.assertEqual(key.public_blob.comment, "test_rsa.key.pub")
        # Delve into blob contents, for test purposes
        msg = Message(key.public_blob.key_blob)
        self.assertEqual(msg.get_text(), "*****@*****.**")
        msg.get_string()
        e = msg.get_mpint()
        n = msg.get_mpint()
        self.assertEqual(e, key.public_numbers.e)
        self.assertEqual(n, key.public_numbers.n)
        # Serial number
        self.assertEqual(msg.get_int64(), 1234)

        # Prevented from loading certificate that doesn't match
        key_path = _support(os.path.join("cert_support", "test_ed25519.key"))
        key1 = Ed25519Key.from_private_key_file(key_path)
        self.assertRaises(
            ValueError,
            key1.load_certificate,
            _support("test_rsa.key-cert.pub"),
        )
示例#38
0
    def __init__(self,
                 serverdns,
                 username=None,
                 pw=None,
                 keyfile=None,
                 keyfile_pw=None,
                 logfile=None):
        self.serverdns = serverdns
        self.cname = self.serverdns.split('.')[0]

        if not logfile:
            logname = time.strftime("%d%b%Y")
            self.logfile = open(
                os.path.join('./logs', '%s-%s.log' % (self.cname, logname)),
                'a')
        else:
            self.logfile = logfile

        self.ssh = SSHClient()
        self.ssh.load_system_host_keys()

        self.username = username
        self.pw = pw
        self.pkey_filename = keyfile
        self.pkey_pw = keyfile_pw

        self.pkey = None
        if self.pkey_filename:
            self.pkey = RSAKey.from_private_key_file(self.pkey_filename,
                                                     password=self.pkey_pw)

        self.chan = None
 def test_simple(self):
     """
     verify that we can establish an ssh link with ourselves across the
     loopback sockets.  this is hardly "simple" but it's simpler than the
     later tests. :)
     """
     host_key = RSAKey.from_private_key_file(_support("test_rsa.key"))
     public_host_key = RSAKey(data=host_key.asbytes())
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assertTrue(not event.is_set())
     self.assertEqual(None, self.tc.get_username())
     self.assertEqual(None, self.ts.get_username())
     self.assertEqual(False, self.tc.is_authenticated())
     self.assertEqual(False, self.ts.is_authenticated())
     self.ts.start_server(event, server)
     self.tc.connect(
         hostkey=public_host_key, username="******", password="******"
     )
     event.wait(1.0)
     self.assertTrue(event.is_set())
     self.assertTrue(self.ts.is_active())
     self.assertEqual("slowdive", self.tc.get_username())
     self.assertEqual("slowdive", self.ts.get_username())
     self.assertEqual(True, self.tc.is_authenticated())
     self.assertEqual(True, self.ts.is_authenticated())
示例#40
0
 def test_3_simple(self):
     """
     verify that we can establish an ssh link with ourselves across the
     loopback sockets.  this is hardly "simple" but it's simpler than the
     later tests. :)
     """
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     event = threading.Event()
     server = NullServer()
     self.assert_(not event.isSet())
     self.assertEquals(None, self.tc.get_username())
     self.assertEquals(None, self.ts.get_username())
     self.assertEquals(False, self.tc.is_authenticated())
     self.assertEquals(False, self.ts.is_authenticated())
     self.ts.start_server(event, server)
     self.tc.connect(hostkey=public_host_key,
                     username='******',
                     password='******')
     event.wait(1.0)
     self.assert_(event.isSet())
     self.assert_(self.ts.is_active())
     self.assertEquals('slowdive', self.tc.get_username())
     self.assertEquals('slowdive', self.ts.get_username())
     self.assertEquals(True, self.tc.is_authenticated())
     self.assertEquals(True, self.ts.is_authenticated())
示例#41
0
    def _set_authentication(self, password, private_key, private_key_pass):
        '''Authenticate the transport. prefer password if given'''
        if password is None:
            # Use Private Key.
            if not private_key:
                # Try to use default key.
                if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
                    private_key = '~/.ssh/id_rsa'
                elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
                    private_key = '~/.ssh/id_dsa'
                else:
                    raise CredentialException("No password or key specified.")

            if isinstance(private_key, (AgentKey, RSAKey)):
                # use the paramiko agent or rsa key
                self._tconnect['pkey'] = private_key
            else:
                # isn't a paramiko AgentKey or RSAKey, try to build a
                # key from what we assume is a path to a key
                private_key_file = os.path.expanduser(private_key)
                try:  # try rsa
                    self._tconnect['pkey'] = RSAKey.from_private_key_file(
                        private_key_file, private_key_pass)
                except paramiko.SSHException:   # if it fails, try dss
                    # pylint:disable=r0204
                    self._tconnect['pkey'] = DSSKey.from_private_key_file(
                        private_key_file, private_key_pass)
示例#42
0
 def test_load_rsa_password(self):
     key = RSAKey.from_private_key_file(_support("test_rsa_password.key"),
                                        "television")
     self.assertEqual("ssh-rsa", key.get_name())
     self.assert_key_fingerprints(key, FINGER_RSA)
     self.assertEqual(PUB_RSA.split()[1], key.get_base64())
     self.assertEqual(1024, key.get_bits())
示例#43
0
def exc_command(hostname, port, command_line):
    """
    Depends on the 'paramiko' module
    :param hostname:Type str
        The unique id for host.
        It can be the hostname if the /etc/hosts was configured.Or use the ip address of host.
    :param port:Type int
        SSH port number.
    :param command_line:Type str
        The command you want to execute.
    :return:Type str
        The output info or err info after the command has been executed.
    """
    private_key = RSAKey.from_private_key_file('/home/iptatest/.ssh/id_rsa')
    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    try:
        client.connect(hostname, port, username='******', pkey=private_key, timeout=5)
        stdin, stdout, stderr = client.exec_command(command_line)
        message = str(stderr.read(), encoding='utf-8')
        if not message:
            result = str(stdout.read(), encoding='utf-8')
            return result.strip('\n')
        else:
            return message.strip('\n')
    except socket.error:
        return "Socket error."
    except ssh_exception.SSHException:
        return "SSH authenticated failed.Please check the private_key."
    finally:
        client.close()
示例#44
0
def ensure_ssh_key(name=None, base_name=__name__, verify_pem_file=True):
    from paramiko import RSAKey
    if name is None:
        from getpass import getuser
        from socket import gethostname
        name = base_name + "." + getuser() + "." + gethostname().split(".")[0]

    try:
        ec2_key_pairs = list(resources.ec2.key_pairs.filter(KeyNames=[name]))
        if verify_pem_file and not os.path.exists(get_ssh_key_path(name)):
            msg = "Key {} found in EC2, but not in ~/.ssh."
            msg += " Delete the key in EC2, copy it to {}, or specify another key."
            raise KeyError(msg.format(name, get_ssh_key_path(name)))
    except ClientError as e:
        expect_error_codes(e, "InvalidKeyPair.NotFound")
        ec2_key_pairs = None

    if not ec2_key_pairs:
        if os.path.exists(get_ssh_key_path(name)):
            ssh_key = RSAKey.from_private_key_file(get_ssh_key_path(name))
        else:
            logger.info("Creating key pair %s", name)
            ssh_key = new_ssh_key()
            makedirs(os.path.dirname(get_ssh_key_path(name)), exist_ok=True)
            ssh_key.write_private_key_file(get_ssh_key_path(name))
        resources.ec2.import_key_pair(
            KeyName=name, PublicKeyMaterial=get_public_key_from_pair(ssh_key))
        logger.info("Imported SSH key %s", get_ssh_key_path(name))
    try:
        subprocess.check_call(["ssh-add", get_ssh_key_path(name)], timeout=5)
    except Exception as e:
        logger.warn(
            "Failed to add %s to SSH keychain: %s. Connections may fail",
            get_ssh_key_path(name), e)
    return name
    def setup_test_server(
        self, client_options=None, server_options=None, connect_kwargs=None
    ):
        host_key = RSAKey.from_private_key_file(_support("test_rsa.key"))
        public_host_key = RSAKey(data=host_key.asbytes())
        self.ts.add_server_key(host_key)

        if client_options is not None:
            client_options(self.tc.get_security_options())
        if server_options is not None:
            server_options(self.ts.get_security_options())

        event = threading.Event()
        self.server = NullServer()
        self.assertTrue(not event.is_set())
        self.ts.start_server(event, self.server)
        if connect_kwargs is None:
            connect_kwargs = dict(
                hostkey=public_host_key,
                username="******",
                password="******",
            )
        self.tc.connect(**connect_kwargs)
        event.wait(1.0)
        self.assertTrue(event.is_set())
        self.assertTrue(self.ts.is_active())
示例#46
0
 def test_3_load_rsa_password(self):
     key = RSAKey.from_private_key_file(test_path("test_rsa_password.key"), "television")
     self.assertEqual("ssh-rsa", key.get_name())
     exp_rsa = b(FINGER_RSA.split()[1].replace(":", ""))
     my_rsa = hexlify(key.get_fingerprint())
     self.assertEqual(exp_rsa, my_rsa)
     self.assertEqual(PUB_RSA.split()[1], key.get_base64())
     self.assertEqual(1024, key.get_bits())
示例#47
0
 def test_6_compare_rsa(self):
     # verify that the private & public keys compare equal
     key = RSAKey.from_private_key_file('tests/test_rsa.key')
     self.assertEquals(key, key)
     pub = RSAKey(data=str(key))
     self.assert_(key.can_sign())
     self.assert_(not pub.can_sign())
     self.assertEquals(key, pub)
示例#48
0
 def test_6_compare_rsa(self):
     # verify that the private & public keys compare equal
     key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
     self.assertEqual(key, key)
     pub = RSAKey(data=key.asbytes())
     self.assertTrue(key.can_sign())
     self.assertTrue(not pub.can_sign())
     self.assertEqual(key, pub)
示例#49
0
 def start_server(self):
     host_key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
     self.public_host_key = RSAKey(data=host_key.asbytes())
     self.ts.add_server_key(host_key)
     self.event = threading.Event()
     self.server = NullServer()
     self.assertTrue(not self.event.is_set())
     self.ts.start_server(self.event, self.server)
示例#50
0
 def start_server(self):
     host_key = RSAKey.from_private_key_file('tests/test_rsa.key')
     self.public_host_key = RSAKey(data=str(host_key))
     self.ts.add_server_key(host_key)
     self.event = threading.Event()
     self.server = NullServer()
     self.assert_(not self.event.isSet())
     self.ts.start_server(self.event, self.server)
示例#51
0
def get_public_rsa_fingerprint(pubkey_location):
    try:
        k = RSAKey.from_private_key_file(pubkey_location)
    except paramiko.SSHException:
        raise exception.SSHError("Invalid RSA private key file: %s" %
                                 pubkey_location)
    md5digest = hashlib.md5(str(k)).hexdigest()
    return insert_char_every_n_chars(md5digest, ':', 2)
示例#52
0
 def test_3_load_rsa_password(self):
     key = RSAKey.from_private_key_file('tests/test_rsa_password.key', 'television')
     self.assertEquals('ssh-rsa', key.get_name())
     exp_rsa = FINGER_RSA.split()[1].replace(':', '')
     my_rsa = hexlify(key.get_fingerprint())
     self.assertEquals(exp_rsa, my_rsa)
     self.assertEquals(PUB_RSA.split()[1], key.get_base64())
     self.assertEquals(1024, key.get_bits())
示例#53
0
 def getIdentityKey(self):
     keyfile = os.path.abspath(os.path.join(self.getLocalBuildoutPath(),'hostout_rsa'))
     keyfile = self.options.get('identity-file', keyfile)
     if not os.path.exists(keyfile):
         key = RSAKey.generate(1024)
         key.write_private_key_file(keyfile)
     else:
         key = RSAKey.from_private_key_file(keyfile)
     return keyfile, "ssh-rsa %s hostout@hostout" % key.get_base64()
示例#54
0
 def connect_ssh(self, ip, key_name):
     # TODO: set a more reasonable connection timeout time
     key = RSAKey.from_private_key_file("/tmp/%s.pem" % key_name)
     client = SSHClient()
     client.load_system_host_keys()
     client.set_missing_host_key_policy(WarningPolicy())
     client.connect(ip, username="******", pkey=key)
     stdin, stdout, stderr = client.exec_command("uptime")
     print "uptime: ", stdout.read()
     return client
示例#55
0
文件: sftp.py 项目: quarkslab/irma
    def _connect(self):
        self._conn = Transport((self._host, self._port))
        self._conn.window_size = pow(2, 27)
        self._conn.packetizer.REKEY_BYTES = pow(2, 32)
        self._conn.packetizer.REKEY_PACKETS = pow(2, 32)
        if self._auth == 'key':
            pkey = RSAKey.from_private_key_file(self._key_path)
            self._conn.connect(username=self._user, pkey=pkey)
        else:
            self._conn.connect(username=self._user, password=self._passwd)

        self._client = SFTPClient.from_transport(self._conn)
示例#56
0
文件: main.py 项目: choppsv1/jdsu-ocm
def main (*margs):
    parser = argparse.ArgumentParser("JDSU-OCM Netconf Server")

    parser.add_argument("--server-port", type=int, default=830, help="Port for netconf to listen on")
    parser.add_argument("--server-username", default="admin", help="Netconf user")
    parser.add_argument("--server-password", default="admin", help="Netconf password")
    parser.add_argument("--server-host-key", help="Server SSH Host Key")
    parser.add_argument("--device-host", help="The remote JDSU host to run sercat on otherwise local")
    parser.add_argument("--device-name", default="/dev/ttyUSB0", help="The serial port device")
    parser.add_argument("--device-username", help="The username to login with")
    parser.add_argument("--device-password", help="The password to login with")
    parser.add_argument("--device-key", help="SSH Private key to use")
    parser.add_argument("-v", "--verbose", action="store_true", help="Verbose logging")
    parser.add_argument("-d", "--debug", action="store_true", help="Enable debug logging")
    args = parser.parse_args(*margs)

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    elif args.verbose:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.WARNING)
    logger = logging.getLogger(__name__)

    # Mutually exclusive
    if args.device_password and args.device_key:
        logger.critical("Can't specify both --device-key and --device-password")
        sys.exit(1)

    if not args.server_host_key or not os.path.exists(os.path.expanduser(args.server_host_key)):
        logger.critical("Server host ssh key required.")
        sys.exit(1)

    if not args.device_host:
        jdsu = device.LocalOCM(args.device_name, debug=args.debug)
    else:
        if args.device_key:
            password = RSAKey.from_private_key_file(args.device_key)
        else:
            password = args.device_password
        jdsu = device.RemoteOCM(args.device_host,
                                args.device_name,
                                username=args.device_username,
                                password=password,
                                debug=args.debug)

    ncserver = server.NetconfServer(jdsu,
                                    args.server_host_key,
                                    ssh_port=args.server_port,
                                    username=args.server_username,
                                    password=args.server_password,
                                    debug=args.debug)
    ncserver.join()
示例#57
0
 def test_8_sign_rsa(self):
     # verify that the rsa private key can sign and verify
     key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
     msg = key.sign_ssh_data(b'ice weasels')
     self.assertTrue(type(msg) is Message)
     msg.rewind()
     self.assertEqual('ssh-rsa', msg.get_text())
     sig = bytes().join([byte_chr(int(x, 16)) for x in SIGNED_RSA.split(':')])
     self.assertEqual(sig, msg.get_binary())
     msg.rewind()
     pub = RSAKey(data=key.asbytes())
     self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg))
示例#58
0
 def test_8_sign_rsa(self):
     # verify that the rsa private key can sign and verify
     key = RSAKey.from_private_key_file('tests/test_rsa.key')
     msg = key.sign_ssh_data(rng, 'ice weasels')
     self.assert_(type(msg) is Message)
     msg.rewind()
     self.assertEquals('ssh-rsa', msg.get_string())
     sig = ''.join([chr(int(x, 16)) for x in SIGNED_RSA.split(':')])
     self.assertEquals(sig, msg.get_string())
     msg.rewind()
     pub = RSAKey(data=str(key))
     self.assert_(pub.verify_ssh_sig('ice weasels', msg))
示例#59
0
    def _check_keypair(self, name, public_key_path, private_key_path):
        connection = self._connect()
        keypairs = connection.get_all_key_pairs()
        keypairs = dict((k.name, k) for k in keypairs)

        # decide if dsa or rsa key is provided
        pkey = None
        is_dsa_key = False
        try:
            pkey = DSSKey.from_private_key_file(private_key_path)
            is_dsa_key = True
        except PasswordRequiredException:
            raise KeypairError(
                "Key `%s` is encrypted with a password. Please, use"
                "an unencrypted key or use ssh-agent" %
                private_key_path)
        except SSHException:
            try:
                pkey = RSAKey.from_private_key_file(private_key_path)
            except PasswordRequiredException:
                raise KeypairError(
                    "Key `%s` is encrypted with a password. Please, use"
                    "an unencrypted key or use ssh-agent" %
                    private_key_path)
            except SSHException:
                raise KeypairError('File `%s` is neither a valid DSA key '
                                   'or RSA key.' % private_key_path)

        # create keys that don't exist yet
        if name not in keypairs:
            log.warning(
                "Keypair `%s` not found on resource `%s`, Creating a new one",
                name, self._url)
            with open(os.path.expanduser(public_key_path)) as f:
                key_material = f.read()
                try:
                    # check for DSA on amazon
                    if "amazon" in self._ec2host and is_dsa_key:
                        log.error(
                            "Apparently, amazon does not support DSA keys. "
                            "Please specify a valid RSA key.")
                        raise KeypairError(
                            "Apparently, amazon does not support DSA keys."
                            "Please specify a valid RSA key.")

                    connection.import_key_pair(name, key_material)
                except Exception, ex:
                    log.error(
                        "Could not import key `%s` with name `%s` to `%s`",
                        name, public_key_path, self._url)
                    raise KeypairError(
                        "could not create keypair `%s`: %s" % (name, ex))