利用Paramiko模块远程连接Linux
使用Paramiko模块模拟SSH远程连接到服务器,并执行命令。(支持Tab键补全)
1、安装相关模块:
1)安装 Crypto 模块:
下载源码包解压
安装:
sudo python setup.py build
sudo python setup.py install
2)安装 cryptography-1.2
注意,必须安装低版本,1.5版本报错:
t.start_client() File "/Library/Python/2.7/site-packages/paramiko/transport.py", line 493, in start_client raise e AttributeError: 'EntryPoint' object has no attribute 'resolve'
直接pip安装:
sudo pip install cryptography==1.2
mac下python模块安装路径为:
/Library/Python/2.7/site-packages/
2、远程登录程序:
#!usr/bin/python import os import tty import sys import conf import select import termios import paramiko paramiko.util.log_to_file('conn.log') trans = paramiko.Transport(('ip',22)) trans.start_client() trans.auth_password(username='user',password='password') channel = trans.open_session() channel.get_pty() channel.invoke_shell() oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin) channel.settimeout(0) while True: readlist,writelist,errlist = select.select([channel,sys.stdin],[],[]) if sys.stdin in readlist: input_cmd = sys.stdin.read(1) channel.sendall(input_cmd) if channel in readlist: result = channel.recv(1024) if len(result) == 0: print '\r\n**** EOF ****\r\n' break sys.stdout.write(result.decode()) sys.stdout.flush() finally: termios.tcsetattr(sys.stdin,termios.TCSADRAIN,oldtty) channel.close() trans.close()