def create_new_ssh_client(self): assert self.aws_instance_ip if self.ssh: self.ssh.close() self.logger.info( "Creating SSH client and waiting for SSH to become available...") ssh = paramiko.client.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) timeout = time.monotonic() + 60 while time.monotonic() < timeout: try: ssh.connect( self.aws_instance_ip, username=self.ssh_user, key_filename=os.path.expanduser(self.ssh_key_file), ) break except paramiko.ssh_exception.NoValidConnectionsError: self.logger.info("SSH not ready, yet, sleeping 5 seconds") time.sleep(5) self.ssh = ssh return self.ssh
def __init__(self, host, port=22, username=None, pkey=None, password=None, passphrase=None): # FIXME: auth. Currently it's "whatever paramiko feels like doing" self.client = paramiko.SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.WarningPolicy()) try: self.client.connect(host, port=port, username=username, pkey=pkey, password=password, passphrase=passphrase) except paramiko.PasswordRequiredException as e: raise PasswordRequiredException(str(e)) self.sftp_chan = self.client.get_transport().open_session() self.sftp_chan.invoke_subsystem('sftp') self.sftp_client = paramiko.SFTPClient(self.sftp_chan) self.lock = threading.Lock() self.closed = False
def exploit_with_login_creds(self, port) -> paramiko.SSHClient: user_password_pairs = self._config.get_exploit_user_password_pairs() for user, current_password in user_password_pairs: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) try: ssh.connect(self.host.ip_addr, username=user, password=current_password, port=port) LOG.debug( "Successfully logged in %r using SSH. User: %s, pass (SHA-512): %s)", self.host, user, self._config.hash_sensitive_data(current_password)) self.add_vuln_port(port) self.report_login_attempt(True, user, current_password) return ssh except Exception as exc: LOG.debug( "Error logging into victim %r with user" " %s and password (SHA-512) '%s': (%s)", self.host, user, self._config.hash_sensitive_data(current_password), exc) self.report_login_attempt(False, user, current_password) ssh.close() continue raise FailedExploitationError
def main(): options, server, remote = parse_options() password = None if options.readpass: password = getpass.getpass('Enter SSH password: '******'Connecting to ssh host %s:%d ...' % (server[0], server[1])) try: client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile, look_for_keys=options.look_for_keys, password=password) except Exception as e: print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e)) sys.exit(1) verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1])) try: reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport()) except KeyboardInterrupt: print('C-c: Port forwarding stopped.') sys.exit(0)
def test_invalid_passwd_failure(self): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh.connect('127.0.0.1', username='******', password='******', port=1025) channel = ssh.invoke_shell() # read prompt recv_all(channel) channel.send('passwd remotey\n') stdout = recv_all(channel) open('stdout', 'w').write(stdout) self.assertEqual(stdout, ('passwd remotey\r\nChanging password for ' 'user remotey.\r\nNew BIG-IP password: '******'1234\n') stdout = recv_all(channel) self.assertEqual(stdout, '\r\nRetype new BIG-IP password: '******'12345\n') stdout = recv_all(channel) self.assertEqual(stdout, ('\r\nSorry, passwords do not match\r\npasswd' ': Authentication token manipulation error\r' '\npasswd: password unchanged\r\n[root@hostn' 'ame:Active] testadmin # '))
def check_host(hostname, username=None, password=None, local_site_name=None): """ Checks if we can connect to a host with a known key. This will raise an exception if we cannot connect to the host. The exception will be one of BadHostKeyError, UnknownHostKeyError, or SCMError. """ from django.conf import settings client = get_ssh_client(local_site_name) client.set_missing_host_key_policy(RaiseUnknownHostKeyPolicy()) kwargs = {} # We normally want to notify on unknown host keys, but not when running # unit tests. if getattr(settings, 'RUNNING_TEST', False): client.set_missing_host_key_policy(paramiko.WarningPolicy()) kwargs['allow_agent'] = False try: client.connect(hostname, username=username, password=password, pkey=get_user_key(local_site_name), **kwargs) except paramiko.BadHostKeyException, e: raise BadHostKeyError(e.hostname, e.key, e.expected_key)
def run(self): self.ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy()) self.ssh_client.connect(self.host, port=self.ssh_port, username=self.user) if not self.my_ip: self.my_ip = self.ssh_client.get_transport().sock.getsockname()[0] self.logger.info("Controller will send update to IP {}".format( self.my_ip)) # TODO: add a cli option for the path command = 'LD_LIBRARY_PATH=/opt/beerocks/lib /opt/beerocks/bin/beerocks_cli -a {}'.format( self.my_ip) # create ssh shell ssh_shell = self.ssh_client.invoke_shell() # establish connection in_buff = '' while not in_buff.endswith(':~# '): in_buff += ssh_shell.recv(9999).decode("utf-8") # execute command logger.debug("Starting beerock_cli -a") i, o, e = self.ssh_client.exec_command(command) logger.debug("beerock_cli -a exited") return o.channel.recv_exit_status()
def __init__(self, host=None, username=None, password=None): if host is None or username is None or password is None: return print "Retrieving config..." self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.WarningPolicy()) self.client.connect(host, username=username, password=password) self.client.load_system_host_keys() stdin, stdout, stderr = self.client.exec_command( 'show configuration security policies | display set | no-more') self.policy = stdout.readlines() stdin, stdout, stderr = self.client.exec_command( 'show configuration security address-book global | display set | no-more') self.address_book = stdout.readlines() stdin, stdout, stderr = self.client.exec_command( 'show configuration groups junos-defaults applications | display set | no-more') self.junos_services = stdout.readlines() stdin, stdout, stderr = self.client.exec_command( 'show configuration applications | display set | no-more') self.services = stdout.readlines() self.client.close()
def __init__(self, hostname,port,username,password): self.client = paramiko.SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.WarningPolicy()) self.client.connect(hostname,port,username,password) self.hostname=hostname self.os_type=self.get_os_type()
def _get_connection(self, host, username, password): # Open an SSH connection using the user's SSH config file client = paramiko.SSHClient() client._policy = paramiko.WarningPolicy() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) cfg = {'hostname': host, 'username': username, 'password': password} user_config = ssh_config.lookup(cfg['hostname']) for k in ('hostname', 'username', 'port'): if k in user_config: cfg[k] = user_config[k] if 'proxycommand' in user_config: cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand']) while True: try: client.connect(**cfg) return client except paramiko.ssh_exception.AuthenticationException: print "Authentication failed when connecting to %s" % host raise
def exec_command(address, password, command, username=DEFAULT_USER): """ Execute a ssh command on a host :param address: address of the endpoint :param password: the password :param command: command to be executed :param username: the username, root if not specified :returns stdout: the standard output of the command :raises exc: Exception: if the command returns a non-zero exit status Example: hostname = sshlib.exec_command('192.168.1.5', 'password', 'hostname') """ client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.connect(address, username=username, password=password) try: _, stdout, stderr = client.exec_command(command) status = stdout.channel.recv_exit_status() if status != 0: stderr_message = stderr.read() raise SshException('Ssh command "{command}" exited with status ' 'code {status}. Stderr: {stderr}'.format( command=command, status=status, stderr=stderr_message)) return stdout.read() finally: client.close()
def client(self): if self._client is None: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.WarningPolicy()) cfg = { "hostname": self.host.name, "port": int(self.host.port) if self.host.port else 22, "username": self.host.user, } if self.ssh_config: ssh_config = paramiko.SSHConfig() with open(self.ssh_config) as f: ssh_config.parse(f) for key, value in ssh_config.lookup(self.host.name).items(): if key == "hostname": cfg[key] = value elif key == "user": cfg["username"] = value elif key == "port": cfg[key] = int(value) elif key == "identityfile": cfg["key_filename"] = os.path.expanduser(value[0]) elif key == "stricthostkeychecking" and value == "no": client.set_missing_host_key_policy(IgnorePolicy()) if self.ssh_identity_file: cfg["key_filename"] = self.ssh_identity_file client.connect(**cfg) self._client = client return self._client
def execute_command(self, command): ''' open an ssh session , connect to server and execute an ssh command :param command: command to be executed :return: the command output ''' output = None try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.connect(hostname=self.host, port=self.port, username=self.username, password=self.password) stdin, stdout, stderr = client.exec_command(command) output = stdout.read().decode("utf-8") finally: client.close() return output
def connect_ssh(self): self.ssh_client = paramiko.SSHClient() self.ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy()) self.ssh_client.connect(self.ip, username=self.username, password=self.password)
def _run(self): try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.connect(self.hostname, username=self.username, port=self.port, key_filename=self.keyfile) transport = client.get_transport() transport.set_keepalive(self.keepalive) stdin, stdout, stderr = client.exec_command("gerrit stream-events") self._listen(stdout, stderr) if not stdout.channel.exit_status_ready(): # The stream-event is still running but we are done polling # on stdout most likely due to being asked to stop. # Try to stop the stream-events command sending Ctrl-C stdin.write("\x03") time.sleep(.2) if not stdout.channel.exit_status_ready(): # we're still not ready to exit, lets force the channel # closed now. stdout.channel.close() ret = stdout.channel.recv_exit_status() self.log.debug("SSH exit status: %s" % ret) client.close() if ret and ret not in [-1, 130]: raise Exception("Gerrit error executing stream-events") except: self.log.exception("Exception on ssh event stream:") time.sleep(5)
def __init__(self, hostname: str, username: str, password: str, load_host_keys: bool = True): """ Initialize SSH client with server name and information for authentication :param hostname: The server to connect to. :param username: The username to authenticate as. :param password: A password to use for authentication. :param load_host_keys: Load known host keys from the system to check connection. """ self._client = SSHClient() self._hostname = str(hostname) self._username = str(username) self._password = str(password) if load_host_keys: logging.debug("Loading system host keys...'") self._client.load_system_host_keys() self._client.set_missing_host_key_policy(paramiko.WarningPolicy())
def _connect(self): connect_flag = True try: self._client = paramiko.SSHClient() # self._client.load_system_host_keys() self._client.set_missing_host_key_policy(paramiko.WarningPolicy()) self._client.connect( hostname=self._cfg.get("address").get("value"), port=self._cfg.get("port").get("value"), username=self._cfg.get("user").get("value"), password=self._cfg.get("password").get("value"), look_for_keys=False, timeout=60, ) except Exception as e: logger.debug(f"ssh connect exception: {e.__class__}, {e}") traceback.print_exc() try: self._client.close() except: pass finally: connect_flag = False self._client = None finally: return connect_flag
def test_passwd_success(self): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh.connect('127.0.0.1', username='******', password='******', port=1025) channel = ssh.invoke_shell() # read prompt recv_all(channel) channel.send('passwd remotex\n') stdout = recv_all(channel) self.assertEqual(stdout, ('passwd remotex\r\nChanging password for user' ' remotex.\r\nNew BIG-IP password: '******'1234\n') stdout = recv_all(channel) self.assertEqual(stdout, '\r\nRetype new BIG-IP password: '******'1234\n') stdout = recv_all(channel) self.assertEqual(stdout, ('\r\nChanging password for user remotex.\r' '\npasswd: all authentication tokens updated' ' successfully.\r\n[root@hostname:Active] ' 'testadmin # '))
def tunnel(username, listen_port, server, vnc_port, keyfile): look_for_keys = True remote = ['localhost', vnc_port] client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print("Connecting to ssh host %s:%d ..." % (server[0], server[1])) try: client.connect( server[0], server[1], username=username, key_filename=keyfile, look_for_keys=look_for_keys, password='', ) except Exception as e: print("*** Failed to connect to %s:%d: %r" % (server[0], server[1], e)) self.task_error.append([work_id, 5]) sys.exit() print("Now forwarding remote port %d to %s:%d ..." % (listen_port, remote[0], remote[1])) reverse_forward_tunnel(listen_port, remote[0], remote[1], client.get_transport())
def sshcmd(pwd, port, cmd, textin=''): ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) #f = open(sshkey, 'r') #s = f.read() #keyfile = StringIO(s) #pkey = paramiko.RSAKey.from_private_key(keyfile) try: ssh.connect('bitbsd.org', username='******', port=int(port), key_filename=sshkey, look_for_keys=False) except Exception as e: #print('!!!!!!!!!!!!!!!' + sshkey) #print(e) ssh.connect('bitbsd.org', username='******', port=int(port), password=str(pwd)) #chan = ssh.get_transport().open_session() stdin, stdout, stderr = ssh.exec_command(cmd) stdin.write(textin) stdin.flush() return stdout.read().decode('utf-8')
def _exec_lcu_paramiko(self, cmdline, backgroundJOB=False): lcuprompt = "LCUp>" if self.DryRun: preprompt = "(dryrun)" else: preprompt = "" if backgroundJOB is True: cmdline = "(( " + cmdline + " ) > " + self.lcuHome + "lofarctl.log 2>&1) &" if self.verbose: print("{} {} {}".format(preprompt, lcuprompt, cmdline)) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) cfg = {'hostname': self.hostname, 'username': self.user} user_config = ssh_config.lookup(cfg['hostname']) for k in ('hostname', 'username', 'port'): if k in user_config: cfg[k] = user_config[k] if 'proxycommand' in user_config: cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand']) client.connect(**cfg) stdin, stdout, stderr = client.exec_command(cmdline) print(stdout.read()) client.close()
def exploit_with_ssh_keys(self, port) -> paramiko.SSHClient: user_ssh_key_pairs = self._config.get_exploit_user_ssh_key_pairs() for user, ssh_key_pair in user_ssh_key_pairs: # Creating file-like private key for paramiko pkey = io.StringIO(ssh_key_pair['private_key']) ssh_string = "%s@%s" % (ssh_key_pair['user'], ssh_key_pair['ip']) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) try: pkey = paramiko.RSAKey.from_private_key(pkey) except (IOError, paramiko.SSHException, paramiko.PasswordRequiredException): LOG.error("Failed reading ssh key") try: ssh.connect(self.host.ip_addr, username=user, pkey=pkey, port=port) LOG.debug( "Successfully logged in %s using %s users private key", self.host, ssh_string) self.report_login_attempt(True, user, ssh_key=ssh_string) return ssh except Exception: ssh.close() LOG.debug( "Error logging into victim %r with %s" " private key", self.host, ssh_string) self.report_login_attempt(False, user, ssh_key=ssh_string) continue raise FailedExploitationError
def setUpClass(cls): # Server connection cls.ssh = paramiko.SSHClient() cls.ssh.load_system_host_keys() cls.ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) cls.ssh.connect(**ssh_info) # Makes some files on the server chan = cls.ssh.get_transport().open_session() chan.exec_command( b'if ! echo -ne "/tmp/r\\xC3\\xA9mi" | xargs test -d; then ' # Directory b'echo -ne "/tmp/bien rang\\xC3\\xA9" | xargs -0 mkdir; ' # Files b'echo -ne "' b'/tmp/r\\xC3\\xA9mi\\x00' b'/tmp/bien rang\\xC3\\xA9/file\\x00' b'/tmp/bien rang\\xC3\\xA9/b\\xC3\\xA8te\\x00' b'/tmp/p\\xE9t\\xE9' # invalid UTF-8 here b'" | xargs -0 touch; ' b'fi') assert chan.recv_exit_status() == 0 print("Running tests on %s with %s" % ("Windows" if WINDOWS else "Mac OS X" if MACOS else "POSIX", "Python 3" if PY3 else "Python 2"))
def client(self): if self._client is None: if not HAS_PARAMIKO: raise RuntimeError(( "You must install paramiko package (pip install paramiko) " "to use the paramiko backend")) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.WarningPolicy()) cfg = { "hostname": self.host, "port": int(self.port) if self.port else 22, "username": self.user, } if self.ssh_config: ssh_config = paramiko.SSHConfig() with open(self.ssh_config) as f: ssh_config.parse(f) for key, value in ssh_config.lookup(self.host).items(): if key == "hostname": cfg[key] = value elif key == "user": cfg["username"] = value elif key == "port": cfg[key] = int(value) elif key == "identityfile": cfg["key_filename"] = os.path.expanduser(value[0]) elif key == "stricthostkeychecking" and value == "no": client.set_missing_host_key_policy(IgnorePolicy()) client.connect(**cfg) self._client = client return self._client
def __init__(self, name, host, username=None, password=None): """ performs authentication and tries to connect to the `host`. """ DistributorBase.__init__(self, host, username, password) self.connection = paramiko.client.SSHClient() self.connection.load_system_host_keys() self.connection.set_missing_host_key_policy(paramiko.WarningPolicy()) self.error = "" self.name = name #So we can have multiples tests per host credentials = {} if username and password: credentials = {"username": username, "password": password} elif username: credentials = {"username": username} host_port = host.split(':') if len(host_port) > 1: host = host_port[0] port = int(host_port[1]) else: port = 22 try: self.connection.connect(host, timeout=5, port=port, **credentials) self.connected = True except socket.gaierror, error: self.error = error
def test_node(request): """Runs an SSH call on a node.""" check_auth(request) # trying an ssh connection connection = paramiko.client.SSHClient() connection.load_system_host_keys() connection.set_missing_host_key_policy(paramiko.WarningPolicy()) name = request.matchdict['name'] host, port = urllib.splitport(name) if port is None: port = 22 username, host = urllib.splituser(host) credentials = {} if username is not None and ':' in username: username, password = username.split(':', 1) credentials = {"username": username, "password": password} elif username is not None: password = None credentials = {"username": username} try: connection.connect(host, port=port, timeout=5, **credentials) return 'Connection to %r : OK' % name except (socket.gaierror, socket.timeout), error: return str(error)
def getInfo(self): oaVer = '1.0' log = logging.getLogger(libLogger) try: log.debug('Creating temp file with prefix OA-info') (fd, fname) = tempfile.mkstemp(prefix="OA-info.") except Exception as e: msg = "Exception occured while attempting to create a temp file" raise Exception(msg, e) try: command = 'show oa info' log.debug('Sending ssh command: %s, %s, %s, %s' % (self.uname, self.ip, self.pw, command)) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) hostname = self.ip port = 22 client.connect(hostname, port=port, username=self.uname, password=self.pw) stdin, stdout, stderr = client.exec_command(command) write(fd, stdout.read()) except Exception as e: msg = "Exception occured while attempting to send ssh command %s" \ % (command) raise Exception(msg, e) finally: client.close() try: log.debug('Opening file %s' % (fname)) fd = open(fname) except Exception as e: msg = "Failed to open file %s" % (fname) raise Exception(msg, e) # NOTE: If the OA team changes their command output then this will break. # It's not suppossed to change though pattern = 'Firmware Ver.' Interconnects = [] for line in fd: matches = re.search(pattern, line) if matches: lineAttr = line.split(':') oAver = lineAttr[1] oAver = oAver.rstrip('\n') oAver = oAver.lstrip() else: continue fd.close() return oAver
def startArk(self): print('start ark 受け付けました') # ARKサーバー インスタンスの起動 subprocess.call( "aws ec2 start-instances --instance-ids {}".format(INSTANCEID), shell=True) time.sleep(3) print('インスタンス起動処理完了') # ARKサーバー インスタンスが起動するまで待機 subprocess.call( "aws ec2 wait instance-status-ok --instance-ids {}".format( INSTANCEID), shell=True) time.sleep(3) print('インスタンス起動待機終了') # ARKサーバー インスタンスのホスト名を取得 proc = subprocess.run([ "aws ec2 describe-instances --instance-ids {} --query 'Reservations[*].Instances[*].PublicDnsName' --output text" .format(INSTANCEID) ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) time.sleep(3) print('ARKサーバー インスタンスのホスト名取得完了') proc = proc.stdout.decode("utf-8") proc = proc.replace("\n", "") print('ARKサーバー インスタンスのホスト名:', proc) # SSH接続クライアント作成 DiscordBOT.arkSSHClient = paramiko.SSHClient() DiscordBOT.arkSSHClient.set_missing_host_key_policy( paramiko.WarningPolicy()) DiscordBOT.arkSSHClient.connect(proc, username='******', password='', key_filename='.ssh/discordbot_key') time.sleep(2) print('SSH接続クライアント作成終了') # SSHでarkサーバー起動 print('********su-steam実行') stdin, stdout, stderr = DiscordBOT.arkSSHClient.exec_command( 'su - steam') time.sleep(2) print('********パスワード入力実行') stdin.write('Std0v0mgsSF5\n') stdin.flush() time.sleep(2) print('********arkmanagerstart実行') stdin.write('arkmanager start\n') stdin.flush() time.sleep(2) print('********ARKサーバー起動処理完了') # サーバー起動処理完了のメッセージをdiscordに送信 DiscordBOT.send_text = "<@&746619641706709003> インスタンスの起動とARKサーバーへの接続に成功しました。\n サーバー起動までお待ちください。"
def __init__(self, **kwargs): """Initializing the client.""" super(BrcdFCSanLookupService, self).__init__(**kwargs) self.configuration = kwargs.get('configuration', None) self.create_configuration() self.client = paramiko.SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.WarningPolicy())
def getSSHObject(ip, username, key_filename): if ip is None: raise Exception('Seriously? The host must have an IP address') ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) key = paramiko.RSAKey.from_private_key_file(key_filename) ssh.connect(ip, username=username, pkey=key) return ssh