Home  >  Article  >  Backend Development  >  python paramiko实现ssh远程访问的方法

python paramiko实现ssh远程访问的方法

WBOY
WBOYOriginal
2016-06-06 11:28:121122browse

安装paramiko后,看下面例子:

代码如下:


import paramiko

#设置ssh连接的远程主机地址和端口
t=paramiko.Transport((ip,port))
#设置登录名和密码
t.connect(username=username,password=password)
#连接成功后打开一个channel
chan=t.open_session()
#设置会话超时时间
chan.settimeout(session_timeout)
#打开远程的terminal
chan.get_pty()
#激活terminal
chan.invoke_shell()
然后就可以通过chan.send('command')和chan.recv(recv_buffer)来远程执行命令以及本地获取反馈。
例如:
chan.send('pwd')
print chan.recv(65535)

重点是,有些命令执行的时间长,不适当的receive回来可能得不到想要的结果,可以使用time.sleep()进行等待,或使用一些条件循环。
例如:

代码如下:


str=chan.recv(recv_buffer)
while not str.endswith('#'):
    str=chan.recv(recv_buffer)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn