Home  >  Article  >  Backend Development  >  How to implement ssh remote access using python paramiko

How to implement ssh remote access using python paramiko

高洛峰
高洛峰Original
2017-01-07 16:41:041850browse

After installing paramiko, look at the following example:

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)

The point is that some commands take a long time to execute, and improper receive may not get the desired results. You can use time.sleep(). Wait, or use some conditional loop.
For example:

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

For more related articles on how python paramiko implements ssh remote access, please pay attention to the PHP Chinese website!


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