服务器python密码_python:使用paramiko批量管理服务器(含密钥和密码)

最近在学习python,学一个模块,写一个脚本,方便以后应用。#!/usr/local/bin/python2.7

# -*- coding: utf-8 -*-

'''

使用paramiko模块通过SSH登陆将执行多条命令,需要多次执行登陆操作。

'''

from paramiko import  SSHClient

from paramiko import AutoAddPolicy

from paramiko import RSAKey

class SshServerCMD():

def __init__(self):

#定义服务器IP和用户名和密钥之类

serverfile = "D:\\testtmp\\server_list2.txt"

serverlist = open(serverfile,"r")

for line in serverlist:

#取IP、用户名和密码或者密钥文件等

if len(line.split()) == 2:

self.HostIP = '%s'% line.split()[0]

self.UserName = '%s'% line.split()[1]

self.Private_key = RSAKey.from_private_key_file(filename='D:\\key_pub\\id_rsa2048.ppk')  #操作机的先私钥路径

self.client = SSHClient()

self.Ssh_Pkey(self.HostIP,self.UserName,self.Private_key)

elif len(line.split()) > 2:

self.HostIP = '%s'% line.split()[0]

self.UserName = '%s'% line.split()[1]

self.PassWord = '%s'% line.split()[2]

self.client = SSHClient()

self.SSH_Passwd(self.HostIP,self.UserName,self.PassWord)

else:

print "%s文件列表长度出错,第一列为服务器IP,第二列为服务器用户名,第三列为服务器对应用户密码!" % serverfile

def SSH_Passwd(self,HostIP,UserName,PassWord):

#使用密码登陆

self.client.set_missing_host_key_policy(AutoAddPolicy())

self.client.load_system_host_keys()

self.client.connect(hostname=HostIP,port=22,username=UserName,password=PassWord)   #使用密钥登陆

print 'HOSTIP:"%s" doing command:' % HostIP

self.DoCommand(HostIP)

self.client.close()

print 'HOSTIP:"%s" is close' % HostIP

def Ssh_Pkey(self,HostIP,UserName,Private_key):

#使用密码登陆

self.client.set_missing_host_key_policy(AutoAddPolicy())

self.client.load_system_host_keys()

private_key2 = RSAKey.from_private_key_file(filename='D:/key_pub/id_rsa2048.ppk')  #操作机的先私钥路径

print HostIP,UserName

self.client.connect(hostname=HostIP,port=22,username=UserName,pkey=Private_key)  #使用密钥登陆

print 'HOSTIP:"%s" doing command:' % HostIP

self.DoCommand(HostIP)

self.client.close()

print 'HOSTIP:"%s" is close' % HostIP

def DoCommand(self,HostIP):

CMDList = open("D:\\testtmp\\cmd_list.txt","r")  #执行文件中的命令

RED_COLOR='\033[1;31;48m'  #红 ,配置终端输出的颜色

BLUE_COLOR='\033[1;34;48m'  #红 ,配置终端输出的颜色

RES='\033[0m'

for cmddo in CMDList:

stdin, stdout, stderr = self.client.exec_command(cmddo)

DoOut=stdout.read()

if DoOut =='' :

print '%s"%s" execution result is NULL,please check command!%s' % (BLUE_COLOR,cmddo.split(),RES)

else:

print '%s"%s" execution result:%s' % (RED_COLOR,cmddo.split(),RES)

print DoOut

if __name__ == "__main__":

SshServerCMD()

server_list2.txt文件内容:

IP   用户名

IP   用户名  密码

cmd_list.txt文件内容:(就是命令)

whoami

/sbin/ifconfig

ifconfig

/bin/hostname

执行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值