How to implement ssh remote access using python paramiko

高洛峰
Release: 2017-01-07 16:41:04
Original
1998 people have browsed it

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)
Copy after login

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)
Copy after login

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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template