linux下使用脚本远程登录设备

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
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值