def startConnection(self): """ connection to remote server can launch a thread checking every minute your mailbox... """ #if not self.directory:return #self.parent().close() self.close() client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(str(self.host.text()), username=str(self.username.text()), password=str(self.password.text())) except SSHException: qApp.instance().showErrorMessage("Error", "The ssh session could not be established") except AuthenticationException: qApp.instance().showErrorMessage("Error","Authentication failed") except BadHostKeyException: qApp.instance().showErrorMessage("Error", "the server's host key could not be verified") sftpCp = self.cleaningRepository(client) if sftpCp: sftp = client.open_sftp() self.sftpCopying(sftp) sftp.close() else: self.retrieveDirTree(c, out) self.makeRScript(client) self.makeShellScript(client) if self.interactiveSession.isChecked(): import interactive print ('invoking a shell') chan = client.invoke_shell() chan.send('bash\n') interactive.interactive_shell(chan) chan.close() else: self.launchCommand(client) client.close()
def login(self, instance_id=None, tags=None): if instance_id is not None: self.by_instance_id(instance_id) elif tags is not None: instances = self.by_tag(tags) if len(instances) > 1: raise Exception('You can only login to one instance. For' 'multiple instances you can specify a command to run.') self.ip_address = instances[0].ip_address # Get terminal size # FIXME Support terminal resizing rows,columns = os.popen('stty size', 'r').read().split() try: # Connect to the host client = self._connect_client(self.ip_address) chan = client.invoke_shell(width=int(columns), height=int(rows)) # Start an interactive shell interactive.interactive_shell(chan) # Close everything after logout chan.close() self._close_client(client) except Exception, e: print '*** Caught exception: %s: %s' % (e.__class__, e) try: self._close_client(client) except: pass sys.exit(1)
def interact(): """ 建立交互式shell """ ## interactive文件在当前目录, 是自行编写的 import interactive ps1 = "PS1='[\u@%s \W]\$ '\n" % host login_msg = "clear;echo -e '\\033[32mLogin %s done. Enjoy it.\\033[0m'\n" % host ## paramiko内置日志 paramiko.util.log_to_file('/tmp/inter_debug.log') try: ssh = paramiko.SSHClient() ssh.load_system_host_keys() ## 这一行是必须的, paramiko需要再本地的known_hosts中查找目标主机 ## 如果没有就会拒绝连接 ## AutoAddPolicy()就是自动接受未知的key ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, port, user, passwd) channel = ssh.invoke_shell() ## 可以选择修改命令提示符, 登陆欢迎信息等. ## 在正式进入交互模式之前发送 channel.send(ps1) channel.send(login_msg) interactive.interactive_shell(channel) channel.close() ssh.close() except Exception, e: print str(e)
def connect(self, message): message.reply_channel.send({"accept": True}) self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect(ip, port=port, username=username, password=password, timeout=3) except socket.timeout: message.reply_channel.send({ "text": json.dumps([ 'stdout', '\033[1;3;31mConnect to server time out\033[0m' ]) }) message.reply_channel.send({"accept": False}) return except Exception: message.reply_channel.send({ "text": json.dumps( ['stdout', '\033[1;3;31mCan not connect to server\033[0m']) }) message.reply_channel.send({"accept": False}) return chan = self.ssh.invoke_shell( width=90, height=40, ) multiple_chan[message.reply_channel.name] = chan interactive_shell(chan, message.reply_channel.name)
def run(self,username): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange): client.connect(self.hostname, self.port, self.username, self.password) else: # SSPI works only with the FQDN of the target host hostname = socket.getfqdn(self.hostname) try: client.connect(self.hostname, self.port, self.username, gss_auth=UseGSSAPI, gss_kex=DoGSSAPIKeyExchange) except Exception: #password = getpass.getpass('Password for %s@%s: ' % (self.username, self.hostname)) client.connect(self.hostname, self.port, self.username, self.password) chan = client.invoke_shell() print(repr(client.get_transport())) print('*** Here we go!\n') interactive.interactive_shell(chan,username) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def __init__(self, user, psword, raspiAdress, localAdress, port): with paramiko.SSHClient() as client: client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(raspiAdress, username=user, password=psword) print('connected client') print('opening local server in browswer with ADB') stdin, stdout, stderr = client.exec_command( f'adb shell am start -a android.intent.action.VIEW -d http://{localAdress}:{port}/' ) err = stderr.readlines() if err == ['error: no devices/emulators found\n']: print( '!!!No Android devices found. Check they are plugged in and in developer mode!!!\n' ) elif err != []: print( '!!!There was an error while trying to run adb (Android Debug Bridge)!!!' ) print( 'You can install adb by running in the terminal below:\n' ) print('sudo apt-get install adb') chan = client.invoke_shell() print(repr(client.get_transport())) print("*** opening shell on client ***\n") interactive.interactive_shell(chan) chan.close() except paramiko.ssh_exception.NoValidConnectionsError: print("!!!Connection failed!!!") except paramiko.ssh_exception.AuthenticationException: print("!!!Username or password incorrect!!!") client.close() print('client closed')
def shell_terminal(gateway_user_obj, host_user_obj): try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') # 需要获取hostname,port,username,password参数 client.connect( host_user_obj.host.ip_addr, host_user_obj.host.port, host_user_obj.user, host_user_obj.password, ) log_msg = 'login [%s]' % (host_user_obj.host.hostname) logger.log_record(gateway_user_obj.id, host_user_obj.id, log_msg) chan = client.invoke_shell() print(repr(client.get_transport())) print('*** Here we go!\n') interactive.interactive_shell(chan, gateway_user_obj, host_user_obj) # 补全参数 chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def interactive(self): interactive_ssh = paramiko.SSHClient() interactive_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) interactive_ssh.connect(hostname=self.host, port=self.port, username=self.usrname, password=self.passwd) channel = interactive_ssh.invoke_shell() interactive.interactive_shell(channel) channel.close()
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('***Connecting***') client.connect(bind_host_obj.host.ip_addr, bind_host_obj.host.port, bind_host_obj.remoteuser.username, bind_host_obj.remoteuser.password, timeout=30) cmd_caches = [] chan = client.invoke_shell() print(repr(client.get_transport())) cmd_caches.append( models.AuditLog(user_id=user_obj.id, bind_host_id=bind_host_obj.id, action_type='login', date=datetime.datetime.now())) log_recording(user_obj, bind_host_obj, cmd_caches) interactive.interactive_shell(chan, user_obj, bind_host_obj, cmd_caches, log_recording) chan.close() client.close() except Exception as e: print('Caught Exception:%s:%s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def connect_ssh(host, port, username, password, log_file=None): if re.match('^\d+(.\d+)+$', host) is not None: ip = host else: ip = get_accessible_ssh_tunnels(host, port, only_best=True) assert ip is not None, f'Can not find accessible ip of {host}:{port}' print(f'Start connecting to {ip}:{port}') # 记录日志 reload(socket) if log_file is not None: paramiko.util.log_to_file(log_file) # 建立ssh连接 ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port=int(port), username=username, password=password, compress=True) # 建立交互式shell连接 channel = ssh.invoke_shell() # 建立交互式管道 interactive_shell(channel) # 关闭连接 channel.close() ssh.close()
def shell(self): if not self.active: print "[x] Server Already Active" return 1 session = self.connection_handle.open_session() session.get_pty() session.invoke_shell() interactive.interactive_shell(session) session.close()
def connect(ssh): #建立交互式shell连接 channel = ssh.invoke_shell() #建立交互式管道 interactive.interactive_shell(channel) #关闭连接 channel.close() ssh.close() return
def shell(self, *args, **kwargs): '''Opens a TTY shell''' self.login() if 'self' in kwargs: del kwargs['self'] chan = self.client.invoke_shell(*args, **kwargs) interactive.interactive_shell(chan) chan.close()
def ssh_to_vm(**kwargs): host_name = kwargs['host'] node_details = cloud_hero.get_all_details() if not node_details.get(host_name): sys.exit('No node with name {} found!'.format(host_name)) node_index = 0 nodes_data = node_details[host_name] if len(nodes_data) > 1: nodes_format = ('{index:<10}{node[name]:<25}{node[public_ip]:<20}' '{node[private_ip]:<20}{node[packages]:<20}' '{environment[name]:<20}{environment[id]:<20}') print('Node exists in two environments:') print(nodes_format.format(**PROMPTER_KWARGS)) for index, node_data in enumerate(nodes_data): node_data['node']['packages'] = ','.join( node_data['node']['packages']) print nodes_format.format(index=index, **node_data) user_prompt = 'Pick the node you want to ssh to'.format(nodes_format) node_index = click.prompt(user_prompt, default=0) node = nodes_data[node_index] remote_ip = node['node']['public_ip'] remote_user = node['provider']['username'] # Get key and write it to the local path expanded_file_path = os.path.expanduser(CLOUD_HERO_SSH_KEY) if not os.path.exists(expanded_file_path): ssh_key_content = cloud_hero.list_key()['content'] write_to_file(ssh_key_content, expanded_file_path) os.chmod(expanded_file_path, 0600) # Connect to remote host. try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting to {} ...'.format(remote_ip)) rsa_key = paramiko.RSAKey.from_private_key_file(expanded_file_path) client.connect(remote_ip, username=remote_user, pkey=rsa_key) chan = client.invoke_shell() print('*** Here we go!\n') interactive_shell(chan) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def login(main_ins, ip, port, username, password): # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) except Exception as e: print('*** Connect failed: ' + str(e)) traceback.print_exc() return #sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys( os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys( os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} agent_auth(t, username) if not t.is_authenticated(): manual_auth(t, username, ip, password) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go!\n') interactive.interactive_shell(chan, main_ins, ip, username) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def connect(request): sshclient=paramiko.SSHClient() sshclient.load_system_host_keys() sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: sshclient.connect('192.168.10.3',22,'root','password') except Exception as e: print e else: chan=sshclient.invoke_shell() interactive_shell(chan,request)
def ssh_to_vm(**kwargs): host_name = kwargs['host'] node_details = cloud_hero.get_all_details() if not node_details.get(host_name): sys.exit('No node with name {} found!'.format(host_name)) node_index = 0 nodes_data = node_details[host_name] if len(nodes_data) > 1: nodes_format = ('{index:<10}{node[name]:<25}{node[public_ip]:<20}' '{node[private_ip]:<20}{node[packages]:<20}' '{environment[name]:<20}{environment[id]:<20}') print('Node exists in two environments:') print(nodes_format.format(**PROMPTER_KWARGS)) for index, node_data in enumerate(nodes_data): node_data['node']['packages'] = ','.join(node_data['node']['packages']) print nodes_format.format(index=index, **node_data) user_prompt = 'Pick the node you want to ssh to'.format(nodes_format) node_index = click.prompt(user_prompt, default=0) node = nodes_data[node_index] remote_ip = node['node']['public_ip'] remote_user = node['provider']['username'] # Get key and write it to the local path expanded_file_path = os.path.expanduser(CLOUD_HERO_SSH_KEY) if not os.path.exists(expanded_file_path): ssh_key_content = cloud_hero.list_key()['content'] write_to_file(ssh_key_content, expanded_file_path) os.chmod(expanded_file_path, 0600) # Connect to remote host. try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting to {} ...'.format(remote_ip)) rsa_key = paramiko.RSAKey.from_private_key_file(expanded_file_path) client.connect(remote_ip, username=remote_user, pkey=rsa_key) chan = client.invoke_shell() print('*** Here we go!\n') interactive_shell(chan) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def ssh_command(s): private_key = paramiko.RSAKey.from_private_key_file('.id_rsa') ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(s['target']) channel = ssh.invoke_shell() channel.send('cd ' + s['app_logs_path'] + ';ls -alt\n') time.sleep(0.1) interactive.interactive_shell(channel) channel.close() ssh.close()
def connectHost(hostInfo): print host ssh = paramiko.client.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostInfo['ip'], username=hostInfo['loginUser'], password=hostInfo['loginPWD']) channel = ssh.invoke_shell() interactive.interactive_shell(channel) channel.close ssh.close return
def sshlogin(args, logger): """ sshlogin function """ #is ccd calling us? if so put it to 1 #callback = 1 logger.debug("creating sshClass..") sshC = sshClass() logger.debug("creating socketClass..") # socC = socketClass() server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile = args # socC.tHost = (server,port) #test line -- comment out #socC.tSocks = tuple(('127.0.0.1',9090)) if sshC.method=='key': sshC.keyfile = __builtin__.openany(sshC.keyfile) s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((server, port)) except Exception as e: print 'Connection to %s:%d failed: %s' % (server, port, str(e)) sys.exit(1) logger.debug("assigning socket to sshC") sshC.s = s print "Connecting %s@%s:%d " % (sshC.user,server,port) logger.debug("creating ssh..") sshC.createSSH() logger.debug("authenticate ssh..") r = sshC.authSSH() if not r == sshC.LOGIN_SUCCESSFUL: print 'Authentication failed!' sys.exit(1) sess = sshC.pm.open_channel('session') sess.get_pty() sess.invoke_shell() #after calling everything is f****d up obviously a fd problem #please FIXME interactive.interactive_shell(sess) logging.debug("close") sess.close() return -1
def sshlogin(args, logger): """ sshlogin function """ #is ccd calling us? if so put it to 1 #callback = 1 logger.debug("creating sshClass..") sshC = sshClass() logger.debug("creating socketClass..") # socC = socketClass() server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile = args # socC.tHost = (server,port) #test line -- comment out #socC.tSocks = tuple(('127.0.0.1',9090)) if sshC.method == 'key': sshC.keyfile = __builtin__.openany(sshC.keyfile) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((server, port)) except Exception as e: print 'Connection to %s:%d failed: %s' % (server, port, str(e)) sys.exit(1) logger.debug("assigning socket to sshC") sshC.s = s print "Connecting %s@%s:%d " % (sshC.user, server, port) logger.debug("creating ssh..") sshC.createSSH() logger.debug("authenticate ssh..") r = sshC.authSSH() if not r == sshC.LOGIN_SUCCESSFUL: print 'Authentication failed!' sys.exit(1) sess = sshC.pm.open_channel('session') sess.get_pty() sess.invoke_shell() #after calling everything is f****d up obviously a fd problem #please FIXME interactive.interactive_shell(sess) logging.debug("close") sess.close() return -1
def sshconnect(): host = raw_input('host to connect to (no port)> ') port = input('port> ') user = raw_input('username> ') pwd = getpass.getpass('password> ') client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.connect(host, port, user, pwd) chan = client.invoke_shell() interactive.interactive_shell(chan) chan.close() client.close()
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') #client.connect(hostname, port, username, password) #连接远程机器。 client.connect( bind_host_obj.host.ip, #远程主机的ip bind_host_obj.host.port, #远程主机的端口 bind_host_obj.remote_user.username, #远程主机的远程用户 bind_host_obj.remote_user.password, #远程主机的远程用户密码 timeout=30) #命令缓存队列 cmd_caches = [] #创建通道。 chan = client.invoke_shell() print(repr(client.get_transport())) #连接上了远程主机 print('*** Here we go!\n') #往命令缓存队列中,记录一条日志。 cmd_caches.append( models.AuditLog( user_id=user_obj.id, #堡垒机用户的id bind_host_id=bind_host_obj.id, #远程主机 action_type='login', #动作类型登入,也可以写登出。 cmd=u"登入远程主机。", date=datetime.datetime.now() #日期 )) #把命令缓存写入数据库。 #缺点是,如果断开或者重启,命令缓存的数据就丢失了。 log_recording(user_obj, bind_host_obj, cmd_caches) #调用interactive进行处理。 interactive.interactive_shell(chan, user_obj, bind_host_obj, cmd_caches, log_recording) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def execute(self, command, *args): try: self.connect() transport = self.client.get_transport() self.chan = transport.open_session() self.chan.get_pty() self.chan.exec_command('{} {} {}'.format(self.name, command, ' '.join(args))) interactive.interactive_shell(self.chan) self.close() except Exception as e: try: self.close() except: pass raise AlaudaExecError('Executing \'{}\' failed with \'{}\''.format(command, e))
def execute(self, command, *args): try: self.connect() transport = self.client.get_transport() self.chan = transport.open_session() self.chan.get_pty() self.chan.exec_command('{} {} {}'.format(self.name, command, ' '.join(args))) interactive.interactive_shell(self.chan) self.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: self.close() except: pass sys.exit(1)
def connection(self, ip, user, password, port=22): # 记录日志 paramiko.util.log_to_file('/tmp/test') # 建立ssh连接 ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, user, password, compress=True) # 建立交互式shell连接 channel = ssh.invoke_shell() # 建立交互式管道 interactive.interactive_shell(channel, user, ip) # 关闭连接 channel.close() ssh.close()
def startConnection(self): """ connection to remote server can launch a thread checking every minute your mailbox... """ #if not self.directory:return #self.parent().close() self.close() client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(str(self.host.text()), username=str(self.username.text()), password=str(self.password.text())) except SSHException: qApp.instance().showErrorMessage( "Error", "The ssh session could not be established") except AuthenticationException: qApp.instance().showErrorMessage("Error", "Authentication failed") except BadHostKeyException: qApp.instance().showErrorMessage( "Error", "the server's host key could not be verified") sftpCp = self.cleaningRepository(client) if sftpCp: sftp = client.open_sftp() self.sftpCopying(sftp) sftp.close() else: self.retrieveDirTree(c, out) self.makeRScript(client) self.makeShellScript(client) if self.interactiveSession.isChecked(): import interactive print('invoking a shell') chan = client.invoke_shell() chan.send('bash\n') interactive.interactive_shell(chan) chan.close() else: self.launchCommand(client) client.close()
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') #client.connect(hostname, port, username, password) print(bind_host_obj.hosts.ip, bind_host_obj.hosts.port, bind_host_obj.sshusers.username, bind_host_obj.sshusers.password) client.connect(bind_host_obj.hosts.ip, bind_host_obj.hosts.port, bind_host_obj.sshusers.username, bind_host_obj.sshusers.password, timeout=30) cmd_caches = [] chan = client.invoke_shell() print(repr(client.get_transport())) print('*** Here we go!\n') cmd_caches.append( models_db.AuditLog(user_id=user_obj.id, bind_host_id=bind_host_obj.id, action_type='login', date=datetime.datetime.now())) log_recording(user_obj, bind_host_obj, cmd_caches) interactive.interactive_shell(chan, user_obj, bind_host_obj, cmd_caches, log_recording) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: #尝试连接 client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') #client.connect(hostname, port, username, password) client.connect( bind_host_obj.host.ip_addr, # 通过bind_host_obj获取到ip bind_host_obj.host.port, # 通过bind_host_obj获取到 port bind_host_obj.remoteuser.username, # 通过bind_host_obj获取到 用户名 bind_host_obj.remoteuser.password, # 通过bind_host_obj获取到 密码 timeout=30) cmd_caches = [] chan = client.invoke_shell() #调用shell print(repr(client.get_transport())) print('*** Here we go!\n') cmd_caches.append( models.AuditLog( user_id=user_obj.id, bind_host_id=bind_host_obj.id, action_type='login', date=datetime.datetime.now())) #一行一条命令,以用户名,绑定主机id 时间 log_recording(user_obj, bind_host_obj, cmd_caches) #将命令写入到数据库下. interactive.interactive_shell(chan, user_obj, bind_host_obj, cmd_caches, log_recording) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() # create SSHClient object client.load_system_host_keys() # 加载用户的.ssh密钥文件 client.set_missing_host_key_policy( paramiko.WarningPolicy()) # 允许连接不在know_hosts文件中的主机 print('*** Connecting...') # client.connect(hostname, port, username, password) client.connect(bind_host_obj.host.ip, bind_host_obj.host.port, bind_host_obj.remote_user.username, bind_host_obj.remote_user.password, timeout=30) # cmd_caches = [] chan = client.invoke_shell( ) # Start an interactive shell session on the SSH server. print(repr(client.get_transport())) print('*** Here we go!\n') log_item = models.AuditLog( user_id=user_obj.id, bind_host_id=bind_host_obj.id, action_type='login', date=datetime.datetime.now()) # 设定AuditLog表中各字段值 log_recording(log_item) interactive.interactive_shell(chan, user_obj, bind_host_obj, log_recording) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def active_shell(instance, user_name, port=22): ''' Leave a shell active __________ parameters - instance : dict. Response dictionary from ec2 instance describe_instances method - user_name : string. SSH username for accessing instance, default usernames for AWS images can be found at https://alestic.com/2014/01/ec2-ssh-username/ - port : port to use to connect to the instance ''' client = connect_to_instance(instance['PublicIpAddress'], instance['KeyName'], username=user_name, port=port) console = client.invoke_shell() console.keep_this = client session = console.get_transport().open_session() session.get_pty() session.invoke_shell() interactive.interactive_shell(session) session.close() return True
def ssh_login(user_obj, bind_host_obj, mysql_engine, log_recording): # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print("*** Connecting...") # client.connect(hostname, port, username, password) client.connect( bind_host_obj.host.ip_addr, bind_host_obj.host.port, bind_host_obj.remoteuser.username, bind_host_obj.remoteuser.password, timeout=30, ) cmd_caches = [] chan = client.invoke_shell() print(repr(client.get_transport())) print("*** Here we go!\n") cmd_caches.append( models.AuditLog( user_id=user_obj.id, bind_host_id=bind_host_obj.id, action_type="login", date=datetime.datetime.now() ) ) log_recording(user_obj, bind_host_obj, cmd_caches) interactive.interactive_shell(chan, user_obj, bind_host_obj, cmd_caches, log_recording) chan.close() client.close() except Exception as e: print("*** Caught exception: %s: %s" % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
class DemoSimple(object): def __init__(self, hostname, port, loginuser, username, pw): self.hostname = hostname self.port = port self.loginuser = loginuser self.username = username self.pw = pw def connect(self): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.hostname, self.port)) except Exception, e: print '*** Connect failed: ' + str(e) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print '*** SSH negotiation failed.' sys.exit(1) if not t.is_authenticated(): t.auth_password(self.username, self.pw) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print '*** Here we go!' print interactive.interactive_shell(chan, self.loginuser, self.username, self.hostname) chan.close() t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def createConnect(hostname,port,username,password): print hostname, port, username, password try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') client.connect(hostname, port, username, password) chan = client.invoke_shell() print(repr(client.get_transport())) print('*** Here we go!\n') interactive.interactive_shell(chan) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def netmiko_interactive(task): host = task.host try: net_connect = task.host.get_connection("netmiko", task.nornir.config) except ValueError: print("Login process timed out looking for prompt.") print("Use optional argument -f <global_delay_factor>") print("eg -f2, and increase until login success.") sys.exit() except NetMikoAuthenticationException: print("Authentication failure. Check credentials.") sys.exit() except NetMikoTimeoutException: print("Login timeout failure.") sys.exit() if AUTOENABLE: netmiko_extras = host.get_connection_parameters("netmiko").extras #Skip if no enable secret if netmiko_extras.get('secret', None): try: net_connect.enable() except ValueError as e: print("Incorrect enable password.") if SHELL_LOG: stdout_tee = TeeStdOut(f'{LOG_DIR}/{host}.log', LOG_MODE) #TODO: Print your own login banner? print(net_connect.find_prompt(), end='') sys.stdout.flush() interactive.interactive_shell(net_connect.remote_conn) if SHELL_LOG: stdout_tee.close()
def do_ssh(self, arg): """\rRun an ssh session\n""" args = arg.split() if len(args) != 3: print "Usage: ssh <host:port> <user> <pass>\n" return host = args[0].split(":")[0] port = int(args[0].split(":")[1]) user = args[1] passwd = args[2] #paramiko_log_file = "paramiko.log" #paramiko.util.log_to_file(paramiko_log_file) try: pol = sshpolicy() client = paramiko.SSHClient() client.set_missing_host_key_policy(pol) client.connect(host, port=port, username=user, password=passwd) chan = client.invoke_shell() interactive.interactive_shell(chan) chan.close() except: traceback.print_exc() try: client.close() except: pass #os.unlink(paramiko_log_file) return
def ssh_session(bind_host_user, user_obj): # now connect hostname = bind_host_user.host.ip_addr #自动输入 主机名 port = bind_host_user.host.port #端口 username = bind_host_user.host_user.username password = bind_host_user.host_user.password try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #生成socket连接 sock.connect((hostname, port)) except Exception as e: print('*** Connect failed: ' + str(e)) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) #使用paramiko的方法去连接服务器执行命令! try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') if not t.is_authenticated(): manual_auth(t, username, password) #密码校验 if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() # terminal chan.invoke_shell() print('*** Here we go!\n') session_obj = models.SessionLog.objects.create(account=user_obj.account, host_user_bind=bind_host_user) interactive.interactive_shell(chan, session_obj)#开始进入交换模式· chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def login(main_ins,h): ip,port,username,password=h.host.ip_addr,h.host.port,h.host_user.username,h.host_user.password # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) except Exception as e: print('*** Connect failed: ' + str(e)) main_ins.flush_cmd_input(str(e),h,1) main_ins.flush_cmd_input('--session closed--',h,2) #traceback.print_exc() return #sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} agent_auth(t, username) if not t.is_authenticated(): manual_auth(t, username, ip,password,h,main_ins) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go! ***\n') main_ins.flush_cmd_input('---- Logged in! ----',h,1) main_ins.flush_audit_log(h) interactive.interactive_shell(chan,main_ins,ip,username,h) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) main_ins.flush_cmd_input(str(e),h,1) main_ins.flush_cmd_input('--session closed--',h,2) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def login(main_ins, h): ip, port, username, password = h.host.ip_addr, h.host.port, h.host_user.username, h.host_user.password # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(15) sock.connect((ip, port)) except Exception as e: print ("*** Connect failed: " + str(e)) main_ins.flush_cmd_input(str(e), h, 1) main_ins.flush_cmd_input("--session closed--", h, 2) # traceback.print_exc() return # sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print ("*** SSH negotiation failed.") sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser("~/.ssh/known_hosts")) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser("~/ssh/known_hosts")) except IOError: # print('*** Unable to open host keys file') keys = {} agent_auth(t, username) if not t.is_authenticated(): manual_auth(t, username, ip, password, h, main_ins) if not t.is_authenticated(): print ("*** Authentication failed. :(") t.close() sys.exit(1) chan = t.open_session() # t_width,t_height = get_terminal_size() chan.get_pty(term="vt100") chan.invoke_shell() print ("*** Login success ***\n") main_ins.flush_cmd_input("---- Logged in! ----", h, 1) main_ins.flush_audit_log(h) interactive.interactive_shell(chan, main_ins, ip, username, h) chan.close() t.close() except Exception as e: print ("\033[31;1m%s\033[0m" % str(e)) main_ins.flush_cmd_input(str(e), h, 1) main_ins.flush_cmd_input("--session closed--", h, 2) # traceback.print_exc() try: t.close() except: pass
if len(username) == 0: username = default_username agent_auth(t, username) if not t.is_authenticated(): manual_auth(username, remote_ip, web_username) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print '*** Login Success!' print interactive.interactive_shell(chan,web_username,hostname) chan.close() t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) # traceback.print_exc() try: t.close() except: pass sys.exit(1)
def interactive_shell(self): self.chan = self.client.invoke_shell() print('*** interactive!\n') interactive.interactive_shell(self.chan)
def ssh_login(user_obj, host_and_sysuser_obj, log_record): hostname = host_and_sysuser_obj.host.ip_addr port = host_and_sysuser_obj.host.port username = host_and_sysuser_obj.sysuser.username auth_type = host_and_sysuser_obj.sysuser.auth_type # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') if auth_type == u'SSH/KEY': auth_key(t, username) else: password = host_and_sysuser_obj.sysuser.password auth_pw(t, username, password) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) log_info_caches = [] # 待存入数据库的命令缓存 chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go!\n') log_info_caches.append(db_modles.AuditLog(user_id=user_obj.id, host_and_sysuser_id=host_and_sysuser_obj.id, action_type="login", date=datetime.datetime.now() )) log_record(user_obj, host_and_sysuser_obj, log_info_caches) interactive.interactive_shell(chan, user_obj, host_and_sysuser_obj, log_info_caches, log_record) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except Exception: pass sys.exit(1)
def ssh_login(): port = 22 auth_type = u'' hostname = input("hostname==>") username = input("username==>") password = input("password==>") # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') if auth_type == u'SSH/KEY': auth_key(t, username) else: # password = host_and_sysuser_obj.sysuser.password auth_pw(t, username, password) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print('*** Here we go!\n') interactive.interactive_shell(chan) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except Exception: pass sys.exit(1)
#if len(username) == 0: # username = default_username agent_auth(t, username) if not t.is_authenticated(): manual_auth(username, hostname) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print '*** Here we go!' print interactive.interactive_shell(chan,username) chan.close() t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: t.close() except: pass sys.exit(1)
__author__ = 'ibm001' # -*- coding: utf-8 -*- import paramiko import interactive #记录日志 paramiko.util.log_to_file('/tmp/test.log') #建立ssh连接 ssh=paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('20.26.12.206',port=22,username='******',password='******') #建立交互式shell连接 channel=ssh.invoke_shell() #建立交互式管道 interactive.interactive_shell(channel) #关闭连接 channel.close() ssh.close()
#!/usr/bin/env python #_*_coding:utf-8_*_ ''' SSHÔ¶³ÌµÇ½µ÷Óà ''' import os,sys,paramiko,time,multiprocessing import interactive ip = sys.argv[1] username = sys.argv[2] password = sys.argv[3] try: port = sys.argv[4] except IndexError: port = 22 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password) channel = ssh.invoke_shell() interactive.interactive_shell(channel, ip, username) channel.close() ssh.close()
#manual_auth(username, hostname) manual_auth(username, hostname,mode) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() ''' record login faile to opslog table''' track_mark = MultiRunCounter.AddNumber() logger.RecordLogSummary('CREATE','TriConnector',track_mark,username,connect_cmd,"1",django_loginuser,"success",1,0) #print '*** Here we go!' print interactive.interactive_shell(chan,django_loginuser,hostname) chan.close() t.close() #except Exception, e: except (Exception, paramiko.AuthenticationException) as error: #print '*** Caught exception: ' + str(error.__class__) + ': ' + str(error) print error ''' record login faile to opslog table''' track_mark = MultiRunCounter.AddNumber() logger.RecordLogSummary('CREATE','TriConnector',track_mark,username,connect_cmd,"1",django_loginuser,error,0,1) #traceback.print_exc() try: t.close() except:
def interactive_shell(self, ser): self.channel = self.ssh.invoke_shell() interactive.interactive_shell(self.channel, ser)
def launch(hostname, port, username, password): # setup logging paramiko.util.log_to_file('demo.log') # now connect try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hostname, port)) except Exception as e: print('*** Connect failed: ' + str(e)) traceback.print_exc() sys.exit(1) try: t = paramiko.Transport(sock) try: t.start_client() except paramiko.SSHException: print('*** SSH negotiation failed.') sys.exit(1) try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print('*** Unable to open host keys file') keys = {} # check server's host key -- this is important. key = t.get_remote_server_key() if hostname not in keys: print('*** WARNING: Unknown host key!') elif key.get_name() not in keys[hostname]: print('*** WARNING: Unknown host key!') elif keys[hostname][key.get_name()] != key: print('*** WARNING: Host key has changed!!!') sys.exit(1) else: print('*** Host key OK.') t.auth_password(username, password) if not t.is_authenticated(): print('*** Authentication failed. :(') t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print type(chan) interactive.interactive_shell(chan) chan.close() t.close() except Exception as e: print('*** Caught exception: ' + str(e.__class__) + ': ' + str(e)) traceback.print_exc() try: t.close() except: pass sys.exit(1)
if len(username) == 0: username = default_username agent_auth(t, username) if not t.is_authenticated(): manual_auth(username, hostname) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print '*** Here we go!' print interactive.interactive_shell(chan) chan.close() t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: t.close() except: pass sys.exit(1)
def connectToHost(host): # Paramiko client configuration UseGSSAPI = True # enable GSS-API / SSPI authentication DoGSSAPIKeyExchange = True port = 22 # get hostname username = '' if len(host) > 1: hostname = host if hostname.find('@') >= 0: username, hostname = hostname.split('@') else: hostname = input('Hostname: ') if len(hostname) == 0: print('*** Hostname required.') sys.exit(1) if hostname.find(':') >= 0: hostname, portstr = hostname.split(':') port = int(portstr) # get username if username == '': default_username = getpass.getuser() username = input('Username [%s]: ' % default_username) if len(username) == 0: username = default_username if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange): password = getpass.getpass('Password for %s@%s: ' % (username, hostname)) # now, connect and use paramiko Client to negotiate SSH2 across the connection try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print('*** Connecting...') if not UseGSSAPI or (not UseGSSAPI and not DoGSSAPIKeyExchange): client.connect(hostname, port, username, password) else: # SSPI works only with the FQDN of the target host hostname = socket.getfqdn(hostname) try: client.connect(hostname, port, username, gss_auth=UseGSSAPI, gss_kex=DoGSSAPIKeyExchange) except Exception: password = getpass.getpass('Password for %s@%s: ' % (username, hostname)) client.connect(hostname, port, username, password) chan = client.invoke_shell() print(repr(client.get_transport())) print('*** Here we go!\n') interactive.interactive_shell(chan) chan.close() client.close() except Exception as e: print('*** Caught exception: %s: %s' % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
default_username = getpass.getuser() username = raw_input('Username [%s]: ' % default_username) if len(username) == 0: username = default_username agent_auth(t, username) if not t.is_authenticated(): manual_auth(username, hostname) if not t.is_authenticated(): print '*** Authentication failed. :(' t.close() sys.exit(1) chan = t.open_session() chan.get_pty() chan.invoke_shell() print '*** Here we go!' print interactive.interactive_shell(chan) chan.close() t.close() except Exception, e: print '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) traceback.print_exc() try: t.close() except: pass sys.exit(1)
else: print('*** Host key OK.') manual_auth(t, username) if not t.is_authenticated(): msg = '*** Authentication failed. :(' output_queue.push(msg) print(msg) t.close() sys.exit(1) chan = t.open_session() chan.get_pty(term='linux') chan.invoke_shell() print('*** Here we go!\n') interactive.interactive_shell(chan, port) chan.close() t.close() except Exception as e: msg = '*** Caught exception: ' + str(e.__class__) + ': ' + str(e) output_queue.push(msg) print() traceback.print_exc() try: t.close() except: pass sys.exit(1)