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 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_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 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_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 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 init_ssh(self, port=None, user=None, passwd=None, timeout=None): if not self.ssh_inited: port = port or self.port user = user or self.user if user in self.passwd_list: passwd = self.passwd_list[user] passwd = passwd or self.passwd timeout = timeout if timeout is not None else ( self.connect_timeout or Machine.class_connect_timeout) self.port = port self.user = user self.passwd = passwd myLogging.logger.info("Init ssh client [%s@%s:%d]." % (self.user, self.host, self.port)) self.set_missing_host_key_policy(ssh.AutoAddPolicy()) myLogging.logger.info( "Begin to connect to [%s@%s:%d] timeout:[%f]." % (self.user, self.host, self.port, timeout)) self.connect(self.host, port=self.port, username=self.user, password=self.passwd, timeout=timeout) self.ssh_inited = True else: myLogging.logger.debug("Init ssh client again [%s@%s:%d]." % (self.user, self.host, self.port))
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 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 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 __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 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 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 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 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 connect_ssh(ip, username, password=None, client=paramiko.SSHClient, key=None): ssh = client() ssh.set_log_channel('critical_only') ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if key: f = StringIO.StringIO(key) pkey = paramiko.DSSKey(file_obj=f) else: pkey = None try: ssh.connect(ip, username=username, password=password, pkey=pkey) except (paramiko.AuthenticationException, EOFError) as e: raise AuthError(str(e)) return ssh
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): 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 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 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 connect_forward(gw, host, port, user): """ Create a different connect that works with a gateway. We really need to create the socket and destroy it when the connection fails and then retry the connect. """ from state import env from forward_ssh import ForwardSSHClient client = ForwardSSHClient() while True: # Load known host keys (e.g. ~/.ssh/known_hosts) unless user says not to. if not env.disable_known_hosts: client.load_system_host_keys() # Unless user specified not to, accept/add new, unknown host keys if not env.reject_unknown_hosts: client.set_missing_host_key_policy(ssh.AutoAddPolicy()) sock = gw.get_transport().open_channel('direct-tcpip', (host, int(port)), ('', 0)) try: client.connect(host, sock, int(port), user, env.password, key_filename=env.key_filename, timeout=10) client._sock_ = sock return client except (ssh.AuthenticationException, ssh.PasswordRequiredException, ssh.SSHException), e: if e.__class__ is ssh.SSHException and env.password: abort(str(e)) env.password = prompt_for_password(env.password) sock.close() except (EOFError, TypeError): # Print a newline (in case user was sitting at prompt) print('') sys.exit(0)
def querySmallFiles(ip, user, password, command): html = [] html.append("<br><br><table bgcolor=#F9F9F9 border=1 cellspacing=0>") 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: if (row.endswith('+') == False): cols = row.split("|") html.append("<tr>") for col in cols: if ((col != ',') and (col != '')): html.append("<td>") html.append(col) html.append("</td>") html.append("</tr>") html.append("</table>") report = ''.join(html) return report