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!