linux下使用脚本远程登录设备:
使用模块paramiko,远程登录的设备名字为username,设备的ip为ip,设备的密码为password.
1.使用类进行初始化
class RemoteMonitor:
ip = ''
port = 22
username = ''
password = ''
def __init__(self,ip,username,password):
self.ip = ip
self.port = 22
self.username = username
self.password = password
2.进行链接设备的函数
def SSHConnection(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip,22,self.username,self.password)
self.ssh = ssh
3.执行命令的函数
def ExecCommand(self,cmd):
stdin, stdout, stderr = self.ssh.exec_command(cmd)
result = stdout.readlines()
# print (stderr,result,len(result))
return result
4.如果执行的命令需要输入密码则使用ExecCommand1(self,cmd)
def ExecCommand1(self,cmd):
stdin, stdout, stderr = self.ssh.exec_command(cmd,get_pty=True)
stdin.write('self.password'+'\n')
result = stdout.readlines()
return result
总的程序为:
import os
import paramiko
import string
import sys
class RemoteMonitor:
ip = ''
port = 22
username = ''
password = ''
def __init__(self,ip,username,password):
self.ip = ip
self.port = 22
self.username = username
self.password = password
def SSHConnection(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip,22,self.username,self.password)
self.ssh = ssh
def ExecCommand(self,cmd):
stdin, stdout, stderr = self.ssh.exec_command(cmd)
stdin='Ap4K5m'
result = stdout.readlines()
# print (stderr,result,len(result))
return result
def ExecCommand1(self,cmd):
stdin, stdout, stderr = self.ssh.exec_command(cmd,get_pty=True)
stdin.write('Ap4K5m'+'\n')
result = stdout.readlines()
return result
#
monitor = RemoteMonitor(hostname,"nvidia",password)
monitor.SSHConnection()
cmd='top'
result=monitor.ExecCommand()
for line in result:
print line