1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python ssh模块_python ssh之paramiko模块使用

python ssh模块_python ssh之paramiko模块使用

时间:2021-01-19 03:02:54

相关推荐

python ssh模块_python ssh之paramiko模块使用

#coding=utf-8

importparamikoclassSSHConnection(object):def __init__(self, host, port, username, password):

self._host=host

self._port=port

self._username=username

self._password=password

self._transport=None

self._sftp=None

self._client=None

self._connect()#建立连接

def_connect(self):

transport=paramiko.Transport((self._host, self._port))

transport.connect(username=self._username, password=self._password)

self._transport=transport#下载

defdownload(self, remotepath, localpath):if self._sftp isNone:

self._sftp=paramiko.SFTPClient.from_transport(self._transport)

self._sftp.get(remotepath, localpath)#上传

defput(self, localpath, remotepath):if self._sftp isNone:

self._sftp=paramiko.SFTPClient.from_transport(self._transport)

self._sftp.put(localpath, remotepath)#执行命令

defexec_command(self, command):if self._client isNone:

self._client=paramiko.SSHClient()

self._client._transport=self._transport

stdin, stdout, stderr=self._client.exec_command(command)

data=stdout.read()if len(data) >0:print data.strip() #打印正确结果

returndata

err=stderr.read()if len(err) >0:print err.strip() #输出错误结果

returnerrdefclose(self):ifself._transport:

self._transport.close()ifself._client:

self._client.close()if __name__ == "__main__":

conn= SSHConnection('192.168.87.200', 22, 'username', 'password')

localpath= 'hello.txt'remotepath= '/home/hupeng/WorkSpace/Python/test/hello.txt'

print 'downlaod start'conn.download(remotepath, localpath)print 'download end'

print 'put begin'conn.put(localpath, remotepath)print 'put end'conn.exec_command('whoami')

conn.exec_command('cd WorkSpace/Python/test;pwd') #cd需要特别处理

conn.exec_command('pwd')

conn.exec_command('tree WorkSpace/Python/test')

conn.exec_command('ls -l')

conn.exec_command('echo "hello python" > python.txt')

conn.exec_command('ls hello') #显示错误信息

conn.close()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。