环境准备:ubuntu 18.04 python2.7.5 PIP (pip install paramiko模块 pip安装通过 sudo apt install python-pip) H3C交换机 local-user admin 开启service type ssh
利用2.75python paramiko第三方模块,对交换机ssh远程
代码:
encoding=utf-8
import paramiko
import time
client = paramiko.SSHClient()
client.load_system_host_keys()
connect to client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='10.104.144.4',port=22,username='admin',password='123.com!',allow_agent=False,look_for_keys=False)
get shell
ssh_shell = client.invoke_shell()
ready when line endswith '>' or other character
while True:
line = ssh_shell.recv(1024)
#print line
if line and line.endswith('>'):
break;
send command
ssh_shell.sendall( 'system-view' + '\n')
ssh_shell.sendall('interface range GigabitEthernet 1/0/44 to GigabitEthernet 1/0/46' + '\n')
ssh_shell.sendall('shutdown' + '\n')
get result lines
lines = []
while True:
line = ssh_shell.recv(1024)
if line and line.endswith('>'):
break;
lines.append(line)
result = ''.join(lines)
print result
print result