def deleteRemoteKey(self): from logger.Logger import logger import traceback if self.pubkey!=None: try: key=self.pubkey.split(' ')[1] except: key=self.pubkey try: import ssh except: import paramiko as ssh sshClient = ssh.SSHClient() sshClient.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: sshClient.connect(hostname=self.host,timeout=10,username=self.username,password=None,allow_agent=True,look_for_keys=False) cmd="sed \'\\#{key}# D\' -i {authorizedKeysFile}" command = cmd.format(key=key,authorizedKeysFile=self.authorizedKeysFile) (stdin,stdout,stderr)=sshClient.exec_command(command) logger.debug("deleted remote key") err=stderr.readlines() if err!=[]: raise Exception("unable to delete remote key") except: logger.debug("unable to delete remote key") logger.debug(traceback.format_exc())
def test_5_cleanup(self): """ verify that when an SSHClient is collected, its transport (and the transport's packetizer) is closed. """ host_key = ssh.RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = ssh.RSAKey(data=str(host_key)) self.tc = ssh.SSHClient() self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy()) self.assertEquals(0, len(self.tc.get_host_keys())) self.tc.connect(self.addr, self.port, username='******', password='******') self.event.wait(1.0) self.assert_(self.event.isSet()) self.assert_(self.ts.is_active()) p = weakref.ref(self.tc._transport.packetizer) self.assert_(p() is not None) del self.tc # hrm, sometimes p isn't cleared right away. why is that? st = time.time() while (time.time() - st < 5.0) and (p() is not None): time.sleep(0.1) self.assert_(p() is None)
def _open_connection(settings, ip_address): # open up the connection ssh_client = ssh.SSHClient() # autoaccess new keys HOME_DIR = os.path.expanduser("~") known_hosts_path = os.path.join(HOME_DIR, ".ssh", "known_hosts") ssh_client.load_system_host_keys(known_hosts_path) ssh_client.set_missing_host_key_policy(ssh.AutoAddPolicy()) #TODO: handle exceptions if connection does not work. # use private key if exists if os.path.exists(settings.PRIVATE_KEY): privatekeyfile = os.path.expanduser(settings.PRIVATE_KEY) #mykey = ssh_client.RSAKey.from_private_key_file(privatekeyfile) ssh_client.connect(ip_address, username=settings.USER_NAME, timeout=60, key_filename=privatekeyfile) else: print("%s %s %s" % (ip_address, settings.USER_NAME, settings.PASSWORD)) print(ssh_client) ssh_client.connect(ip_address, username=settings.USER_NAME, password=settings.PASSWORD, timeout=60) return ssh_client
def _setup_connection(self): self._ssh = ssh.SSHClient() self._ssh.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: if self.socket_timeout: self._ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.passwd, timeout=self.socket_timeout, allow_agent=False, look_for_keys=False) else: self._ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.passwd, allow_agent=False, look_for_keys=False) except ssh.AuthenticationException: raise SwitchAuthenticationException( "Authentication failed (invalid username and/or passwd)") self._ssh.get_transport().set_keepalive((60)) ssh_channel = self._ssh.invoke_shell() ssh_channel.setblocking(0) return ssh_channel
def queryFileIncreInfo(ip, user, password, command): timeList = [] valfilesList = [] valsizeList = [] client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(ip, port=22, username=user, password=password) stdin, stdout, stderr = client.exec_command(command) out = stdout.read() rows = out.split("\n") for row in rows[3::]: if (row.endswith('+') == False): cols = row.split("|") if (len(cols) > 3): timeList.append(cols[1]) valsizeList.append(float(cols[2])) valfilesList.append(float(cols[3])) line_chart6 = pygal.HorizontalBar(width=650, height=800) line_chart6.x_labels = timeList line_chart6.add('File Count', valsizeList) line_chart6.render_to_png('num_of_files.png') line_chart7 = pygal.HorizontalBar(width=650, height=800) line_chart7.x_labels = timeList line_chart7.add('Total size(G)', valfilesList) line_chart7.render_to_png('total_size_gb.png')
def test_4_auto_add_policy(self): """ verify that SSHClient's AutoAddPolicy works. """ host_key = ssh.RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = ssh.RSAKey(data=str(host_key)) self.tc = ssh.SSHClient() self.tc.set_missing_host_key_policy(ssh.AutoAddPolicy()) self.assertEquals(0, len(self.tc.get_host_keys())) self.tc.connect(self.addr, self.port, username='******', password='******') self.event.wait(1.0) self.assert_(self.event.isSet()) self.assert_(self.ts.is_active()) self.assertEquals('slowdive', self.ts.get_username()) self.assertEquals(True, self.ts.is_authenticated()) self.assertEquals(1, len(self.tc.get_host_keys())) self.assertEquals( public_host_key, self.tc.get_host_keys()['[%s]:%d' % (self.addr, self.port)]['ssh-rsa'])
def remoteProcess(ip, user, pwd): myclient = ssh.SSHClient() myclient.set_missing_host_key_policy(ssh.AutoAddPolicy()) myclient.connect(ip, port=22, username=user, password=pwd) stdin, stdout, stderr = myclient.exec_command("jps -v") returnLine = stdout.read() return returnLine
def connect_to(self, remote_host, user, passwd=None): """Connects to remote host passed as an argument,logs in using user and returns True on success.On failure, logs error message and returns False. >>> auto_obj = Unix() >>> auto_obj.connect_to(socket.getfqdn(),"user",passwd="hur") True """ client = ssh.SSHClient() if passwd is None: key_dir = self.config['COMMON.SSH_DIR'] key_files = [key_dir + '/' + key_file for key_file in \ os.listdir(key_dir)] client.set_missing_host_key_policy(ssh.AutoAddPolicy()) logger = logging.getLogger(__name__) try: if passwd is None: client.connect(remote_host, port=22, username=user,\ key_filename=key_files) else: client.connect(remote_host, port=22, username=user,\ password=passwd) except ssh.AuthenticationException, err: logger = logging.getLogger(__name__) logger.error(user+" Unable to login into "+remote_host+ \ "\nERROR:"+str(err)) logger.info("Continuing with the next host...") self.data['UNIX_MSG'] = str(err) return False
def remote_login(self,command): myclient = ssh.SSHClient() # 新建一个ssh客户端对象 myclient.set_missing_host_key_policy(ssh.AutoAddPolicy()) # 设置成默认自动接受密钥 myclient.connect("10.139.49.79", port=22, username="******", password="******") # 连接远程主机 print command stdin, stdout, stderr = myclient.exec_command(command) print stdout.read() myclient.close()
def ssh_connect(ip='', port=0, username='', passwd=''): sshclient = ssh.SSHClient() sshclient.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: sshclient.connect(ip, port, username, passwd) return sshclient except Exception, e: raise e
def __exec(self,ip,username,password,cmd): myclient = ssh.SSHClient() myclient.set_missing_host_key_policy(ssh.AutoAddPolicy()) myclient.connect(ip, port=22, username=username, password=password,timeout=self.timeout) stdin, stdout, stderr = myclient.exec_command(cmd) return stdout.read()
def get_ssh_client(host): global args client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(host, port=args.port, username=args.user, password=args.password) return client
def sshConn(host, port, username, password): try: sshconn = ssh.SSHClient() sshconn.set_missing_host_key_policy(ssh.AutoAddPolicy()) sshconn.connect(host, port, username, password) return sshconn except Exception,e: print '%s %s' % (e, host) return
def run(self): client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(self.ip,port=22,username='******',password='******',timeout=4) for command in self.commands: stdin,stdout,stderr=client.exec_command(command) # for std in stdout.readline(): # print std; stdout.read() stderr.read() client.close()
def __init__(self, hostname="127.0.0.1", port=10022, username="******", password="******"): self.c = ssh.SSHClient() self.c.set_missing_host_key_policy(ssh.AutoAddPolicy()) self.c.connect(hostname, port=port, username=username, password=password)
def run(self): client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(self.ip,port=22,username='******',password='******',timeout=4) stdin,stdout,stderr = client.exec_command("mkdir aaa") stdout.read() stderr.read() for key in self.dirs: sftp = client.open_sftp() print key,"=",self.dirs[key] sftp.put(key, self.dirs[key]) client.close()
def get_ssh_client(host): global args try: client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(host, port=args.port, username=args.user, password=args.password) except Exception, e: print host, e misclog.error("%s: %s" % (host, e))
def sftpPut(host, port, username, password, src_path, dst_path): try: sshconn = ssh.SSHClient() sshconn.set_missing_host_key_policy(ssh.AutoAddPolicy()) sshconn.connect(host, port, username, password) sftp = sshconn.open_sftp() sftp.put(src_path, dst_path) sshconn.close() return 0 except Exception, e: return e
def connect_host(ip, port, username, password): ''' 连接远程主机 ''' client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: client.connect(ip, port = port, username = username, password = password) except Exception,e: print e return False
def _kill_telnet_process(self): ssh = ssh_helper.SSHClient(ssh_helper.SSHClient.JUMP_SERVER_HOST, ssh_helper.SSHClient.JUMP_SERVER_USER, ssh_helper.SSHClient.JUMP_SERVER_PASS) cmd = 'ps -ef | grep q{} | awk \'{}print "kill " $2{}\' | sh'.format( self.telnet_id, '{', '}', ) ssh.stdin.write(cmd + '\n') buf = ssh.read_bytes()
def get_ssh_client(host): global args try: client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(host, port=int(args.port), username='******', password=args.password) except Exception, e: print host, e fastlog.error("%s:%s" % (host, e)) return None
def sshConnect(self, app): # New SSHClient client = ssh.SSHClient() # Default accept unknown keys client.set_missing_host_key_policy(ssh.AutoAddPolicy()) # Connect client.connect(self.remoteMachine, port=22, username=self.remoteUser, password=self.remotePwd) # Execute shell remotely stdin, stdout, stderr = client.exec_command("%s %s" % (app, self.submitTime)) return stdout.read().strip()
def get_ssh_client(host, port, username, password, logger=netlog): try: global args if not host or not port or not username or not password: logger.error ('Args are invalid!') return -1 client = ssh.SSHClient() client.set_missing_host_key_policy(ssh.AutoAddPolicy()) client.connect(host, port=port, username=username, password=password) return client except Exception, e: logger.critical ("%s: %s" % (host, e)) return -1
def __init__(self, host, port): self.telnet_id = random.randint(1, 9999) cmd = 'telnet -e {}{} {} {}'.format(JfwWindows.TELNET_ESCAPE_CHARACTER, self.telnet_id, host, port) # Use a jump server on Windows(dev) ssh = ssh_helper.SSHClient(ssh_helper.SSHClient.JUMP_SERVER_HOST, ssh_helper.SSHClient.JUMP_SERVER_USER, ssh_helper.SSHClient.JUMP_SERVER_PASS) self.ssh = ssh self.write(cmd + '\n')
def remote(cmds): import ssh IP = '192.168.6.121' myclient = ssh.SSHClient() myclient.set_missing_host_key_policy(ssh.AutoAddPolicy()) myclient.connect(IP, port=13780, username='******', password='******') stdin, stdout, stderr = myclient.exec_command(cmds) #return stdout.readlines() return stdout.readlines()
def runCommand(host, port, username, password, command): try: sshconn = ssh.SSHClient() sshconn.set_missing_host_key_policy(ssh.AutoAddPolicy()) sshconn.connect(host, port, username, password) #sshconn.connect('vm1', 22, 'root', '123456') stdin, stdout, stderr = sshconn.exec_command(command) r_stdout = stdout.read() r_stderr = stderr.read() sshconn.close() if r_stdout: return r_stdout if r_stderr: return r_stderr except Exception, e: return e
def run(self): sshClient = ssh.SSHClient() sshClient.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: sshClient.connect(hostname=self.keydistObject.host, username=self.keydistObject.username, password=self.keydistObject.password, allow_agent=False, look_for_keys=False) sshClient.exec_command("module load massive") sshClient.exec_command("/bin/mkdir -p ~/.ssh") sshClient.exec_command("/bin/chmod 700 ~/.ssh") sshClient.exec_command("/bin/touch ~/.ssh/authorized_keys") sshClient.exec_command("/bin/chmod 600 ~/.ssh/authorized_keys") sshClient.exec_command( "/bin/echo \"%s\" >> ~/.ssh/authorized_keys" % self.keydistObject.pubkey) # FIXME The exec_commands above can fail if the user is over quota. sshClient.close() self.keydistObject.keycopiedLock.acquire() self.keydistObject.keycopied = True self.keydistObject.keycopiedLock.release() event = KeyDist.sshKeyDistEvent(KeyDist.EVT_KEYDIST_TESTAUTH, self.keydistObject) logger_debug('CopyIDThread: successfully copied the key') except socket.gaierror as e: logger_debug('CopyIDThread: socket.gaierror : ' + str(e)) self.keydistObject.cancel(message=str(e)) return except socket.error as e: logger_debug('CopyIDThread: socket.error : ' + str(e)) self.keydistObject.cancel(message=str(e)) return except ssh.AuthenticationException as e: logger_debug('CopyIDThread: ssh.AuthenticationException: ' + str(e)) event = KeyDist.sshKeyDistEvent( KeyDist.EVT_KEYDIST_COPYID_NEEDPASS, self.keydistObject, str(e)) except ssh.SSHException as e: logger_debug('CopyIDThread: ssh.SSHException : ' + str(e)) self.keydistObject.cancel(message=str(e)) return if (not self.stopped()): wx.PostEvent(self.keydistObject.notifywindow.GetEventHandler(), event)
def _connect(self): self._ssh = ssh.SSHClient() # automatically add host keys from current user. self._ssh.load_host_keys( os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) # and automatically add new host keys for hosts we haven't seen before. self._ssh.set_missing_host_key_policy(ssh.AutoAddPolicy()) try: self._ssh.connect(self._host, **self._params) except ssh.AuthenticationException as e: raise except Exception as e: print(e) if not hasattr(self, '_sftp'): self._sftp = self._ssh.open_sftp()
def test_3_multiple_key_files(self): """ verify that SSHClient accepts and tries multiple key files. """ host_key = ssh.RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = ssh.RSAKey(data=str(host_key)) self.tc = ssh.SSHClient() self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key) self.tc.connect( self.addr, self.port, username='******', key_filename=['tests/test_rsa.key', 'tests/test_dss.key']) self.event.wait(1.0) self.assert_(self.event.isSet()) self.assert_(self.ts.is_active()) self.assertEquals('slowdive', self.ts.get_username()) self.assertEquals(True, self.ts.is_authenticated())
def Build(self): if not self.builderInstance.online: print(colored('Remote machine is not online!', 'yellow')) return else: clearCache = self.YesNoPrompt( 'Would you like to clear the cache prior to building?') verbose = self.YesNoPrompt('Would you like verbose output?') sshClient = ssh.SSHClient(self.sshUsername, self.builderInstance.GetInstanceIP(), self.sshPassword, self.sshKeyFilePath) if not verbose: print('Starting build (this may take a while!)...') myBuilder = gmBuilder.GMBuilder(self.config, sshClient, verbose) myBuilder.CreateBuildFolders(clearCache=clearCache) myBuilder.DumpOptionFiles() myBuilder.UpdateProject() myBuilder.CompileProject() myBuilder.RetrieveBuild() if self.YesNoPrompt('Would you like to shut down the instance?'): self.builderInstance.Shutdown()