def __init__(self, ip, username="******", timeout=1250, level=xenrt.RC_ERROR, password=None, nowarn=False, port=22): xenrt.TEC().logverbose("SFTP session to %s@%s" % (username, ip)) self.ip = ip self.port = port self.username = username self.timeout = timeout self.level = level self.password = password self.nowarn = nowarn SSHSession.__init__(self, ip, username=username, timeout=timeout, level=level, password=password, nowarn=nowarn, port=port) try: # We do this rather than the simple trans.open_sftp_client() because # if we don't then we don't get a timeout set so we can hang forever c = self.trans.open_channel("session") c.settimeout(timeout) c.invoke_subsystem("sftp") self.client = paramiko.SFTPClient(c) except: self.reply = xenrt.XRT("SFTP connection failed", self.level) self.toreply = 1 self.close()
def __init__(self, connection, root="/", **credentials): """SFTPFS constructor. The only required argument is 'connection', which must be something from which we can construct a paramiko.SFTPClient object. Possibile values include: * a hostname string * a (hostname,port) tuple * a paramiko.Transport instance * a paramiko.Channel instance in "sftp" mode The kwd argument 'root' specifies the root directory on the remote machine - access to files outsite this root wil be prevented. Any other keyword arguments are assumed to be credentials to be used when connecting the transport. """ self._owns_transport = False self._credentials = credentials if isinstance(connection, paramiko.Channel): self.client = paramiko.SFTPClient(connection) else: if not isinstance(connection, paramiko.Transport): connection = paramiko.Transport(connection) self._owns_transport = True if not connection.is_authenticated(): connection.connect(**credentials) self.client = paramiko.SFTPClient.from_transport(connection) self.root = abspath(normpath(root))
def __init__(self, ip, log, username="******", timeout=300, password=None, nowarn=False): self.log = log self.log.debug("SFTP session to %s@%s" % (username, ip)) self.ip = ip self.username = username self.timeout = timeout self.password = password self.nowarn = nowarn SSHSession.__init__(self, ip, log, username=username, timeout=timeout, password=password, nowarn=nowarn) try: # We do this rather than the simple trans.open_sftp_client() because # if we don't then we don't get a timeout set so we can hang forever c = self.trans.open_channel("session") c.settimeout(timeout) c.invoke_subsystem("sftp") self.client = paramiko.SFTPClient(c) except: self.reply = "SFTP connection failed" self.toreply = 1 self.close()
def upload_file(self, host, username, downloadFrom, downloadTo): c = paramiko.SFTPClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print("Connecting to " + host) c.connect(hostname=host, username=username, pkey=self.key) print("Connected to " + host) #Upload file to homr dir tmpFilename = time.strftime("%Y%m%d-%H%M%S") downloadToTmp = "/home/" + username + "/" + tmpFilename print("Upload from " + downloadFrom + " to " + downloadToTmp) c.put(downloadFrom, downloadToTmp) #Clean out old file and replace with new file commands = [ 'rm -f ' + downloadTo, 'mv ' + downloadToTmp + ' ' + downloadTo, 'ls -al ' + downloadTo ] self.execute_cmd(host, username, commands) return { 'message': "Script execution completed. See Cloudwatch logs for complete output" }
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 download_file2local(self, remote_path='/tmp/logs.tgz', local_path='.\\logs.tgz'): t = paramiko.Transport(sock=(self.host, 22)) t.connect(username=self.username, password='******') sftp = paramiko.SFTPClient().from_transport(t, sock=22) sftp.get(remotepath=remote_path, localpath=local_path) t.close()
def download_file(self, host, username, downloadFrom, downloadTo): c = paramiko.SFTPClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print("Connecting to " + host) c.connect(hostname=host, username=username, pkey=self.key) print("Connected to " + host) c.get(downloadFrom, downloadTo) return { 'message': "Script execution completed. See Cloudwatch logs for complete output" }
def _connect_openssh(self): executable = 'ssh' args = [ '-oForwardX11=no', '-oForwardAgent=no', '-oClearAllForwardings=yes', '-oProtocol=2', '-s' ] if self.settings and self.settings['ssh-command']: executable = self.settings["ssh-command"] # default user/port from ssh (could be a per host configuration) if self.port: args += ['-p', str(self.port)] if self.user: args += ['-l', self.user] if self.settings and self.settings['ssh-key']: args += ['-i', self.settings['ssh-key']] if self.settings: if self.settings['ssh-host-keys-check'] != "ssh-config": value = self.settings['ssh-host-keys-check'] args += ['-o', 'StrictHostKeyChecking=%s' % (value, )] if self.settings and self.settings['ssh-known-hosts']: args += [ '-o', 'UserKnownHostsFile=%s' % self.settings['ssh-known-hosts'] ] args += [self.host, 'sftp'] # prepend the executable to the argument list args.insert(0, executable) logging.debug('executing openssh: %s', args) try: proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) except OSError: return False self.transport = None self.sftp = paramiko.SFTPClient(SSHChannelAdapter(proc)) return True
def __init__(self, connection, root_path="/", encoding=None, hostkey=None, username='', password=None, pkey=None, agent_auth=True, no_auth=False, look_for_keys=True): """SFTPFS constructor. The only required argument is 'connection', which must be something from which we can construct a paramiko.SFTPClient object. Possible values include: * a hostname string * a (hostname,port) tuple * a paramiko.Transport instance * a paramiko.Channel instance in "sftp" mode The keyword argument 'root_path' specifies the root directory on the remote machine - access to files outside this root will be prevented. :param connection: a connection string :param root_path: The root path to open :param encoding: String encoding of paths (defaults to UTF-8) :param hostkey: the host key expected from the server or None if you don't require server validation :param username: Name of SFTP user :param password: Password for SFTP user :param pkey: Public key :param agent_auth: attempt to authorize with the user's public keys :param no_auth: attempt to log in without any kind of authorization :param look_for_keys: Look for keys in the same locations as ssh, if other authentication is not succesful """ credentials = dict(username=username, password=password, pkey=pkey) self.credentials = credentials if encoding is None: encoding = "utf8" self.encoding = encoding self.closed = False self._owns_transport = False self._credentials = credentials self._tlocal = thread_local() self._transport = None self._client = None self.hostname = None if isinstance(connection, basestring): self.hostname = connection elif isinstance(connection, tuple): self.hostname = '%s:%s' % connection super(SFTPFS, self).__init__() self.root_path = abspath(normpath(root_path)) if isinstance(connection,paramiko.Channel): self._transport = None self._client = paramiko.SFTPClient(connection) else: if not isinstance(connection,paramiko.Transport): connection = paramiko.Transport(connection) connection.daemon = True self._owns_transport = True if hostkey is not None: key = self.get_remote_server_key() if hostkey != key: raise WrongHostKeyError('Host keys do not match') connection.start_client() if not connection.is_active(): raise RemoteConnectionError(msg='Unable to connect') if no_auth: try: connection.auth_none('') except paramiko.SSHException: pass elif not connection.is_authenticated(): if not username: username = getuser() try: if pkey: connection.auth_publickey(username, pkey) if not connection.is_authenticated() and password: connection.auth_password(username, password) if agent_auth and not connection.is_authenticated(): self._agent_auth(connection, username) if look_for_keys and not connection.is_authenticated(): self._userkeys_auth(connection, username, password) if not connection.is_authenticated(): try: connection.auth_none(username) except paramiko.BadAuthenticationType, e: self.close() allowed = ', '.join(e.allowed_types) raise RemoteConnectionError(msg='no auth - server requires one of the following: %s' % allowed, details=e) if not connection.is_authenticated(): self.close() raise RemoteConnectionError(msg='no auth') except paramiko.SSHException, e: self.close() raise RemoteConnectionError(msg='SSH exception (%s)' % str(e), details=e)
def upload_file2remote(self, local_path='', remote_path=''): t = paramiko.Transport((self.host, 22)) t.connect(username=self.username, password='******') sftp = paramiko.SFTPClient().from_transport(t) sftp.put(localpath=local_path, remotepath=remote_path) t.close()
# def hanshu2(): # pass # if __name__ == '__main__': # print('ture') # import xlwt # a=xlwt.Workbook(encoding='utf-8') # b=a.add_sheet('qwe') # with open('22.txt','r',encoding='utf-8')as w: # c=w.readline() # for i in range len(a): # b.write(i,0,c[i]) # a.save('c.xls') # from hu.pachong2 import jiujiu # jiujiu() import paramiko a = paramiko.SFTPClient() a.set_missing_host_key_policy(paramiko.AutoAddPolicy) a.connect(hostname='', port='', user='', password='') stuin, stuout, stuerr = a.exec_command('') aa = stuout.read().decode('utf-8') print(a) a = paramiko.transport('ip地址', '端口号') a.connect(username='******', password='******') b = paramiko.SFTPClient.from_transport(a) b.get() b.put() b.mkdir() b.rename() b.remove() b.close()