python SSH客户端的交互式和非交互方式

  使用python中有一个paramiko模块来实现python SSH客户端,与SSH服务器交互时,需要注意有交互式和非交互式的区别。

       只执行单条命令,之后就断开链接,可以使用非交互方式。执行多条命令,或者基于前面的输出结果来判断后续要执行的命令,需要使用交互式方式。

       我在写自动化测试用例时,就尝试使用非交互方式去连接一个只支持交互方式的SSH服务器,就怎么也读不到返回结果。换成交互式后就可以了。

       需要注意的是,命令后面记得加“ ”。

      下面内容转自: https://blog.csdn.net/u012322855/article/details/77839929/

  python中有一个paramiko,功能强大,用来做SSH比较方便

  先上代码

import paramiko
class SSHConnection(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

#下载
def download(self, remotepath, localpath):
if self._sftp is None:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.get(remotepath, localpath)

#上传
def put(self, localpath, remotepath):
if self._sftp is None:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.put(localpath, remotepath)

#执行命令
def exec_command(self, command):
if self._client is None:
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() #打印正确结果
return data
err = stderr.read()
if len(err) > 0:
print err.strip() #输出错误结果
return err

def close(self):
if self._transport:
self._transport.close()
if self._client:
self._client.close()

  

  接下来就简单测试一下exec_command这个命令,比较常用

if __name__ == "__main__":
conn = SSHConnection('ip', port, 'username', 'password')

conn.exec_command('ls -ll')
conn.exec_command('cd /home/test;pwd') #cd需要特别处理
conn.exec_command('pwd')
conn.exec_command('tree /home/test')

  exec_command这个函数如果想cd,可以使用pwd这样可以到当前目录而不是初始目录,但是有些情况下,比如chroot,是做不到的,这个时候就需要新的方法


  上代码

ssh = paramiko.SSHClient() #创建sshclient
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #目的是接受不在本地Known_host文件下的主机。
ssh.connect("ip",port,'username','password')
command='chroot /xxx
' 
#conn.write(command)
chan=ssh.invoke_shell()#新函数
chan.send(command+'
')
#
是执行命令的意思,没有
不会执行
time.sleep(10)#等待执行,这种方式比较慢
#这个时候就可以在chroot目录下执行命令了
res=chan.recv(1024)#非必须,接受返回消息
chan.close()

  注意invoke_shell这个函数即可
  另外使用这个函数命令后面记得加“ ”

       

原文地址:https://www.cnblogs.com/lnlvinso/p/10473624.html