批量linux命令执行及文件下载

批量linux命令执行及文件下载

背景

对多台linux服务器使用root权限执行相同查询命令(如用户登录日志、passwd文件、yum日志、端口开放情况等),并将查询结果下载到本地。

函数介绍

  1. Configuration_read()获取IP地址、用户密码、提权方式、下载的文件及保存位置等配置信息;
  2. shell_root_exec(ssh_link,sudo,root_passwd,cmd)进行提权及命令执行
  3. shell_ordinary_exec(ssh_link,cmd,root_passwd=‘’)单sudo命令执行

代码

import time
import paramiko
import pandas
from scp import SCPClient

#root权限多命令执行
#ssh_link:建立一个sshclient对象,对象
#sudo:切换root命令如:sudo - root或sudo -i,字符串
#root_passwd:root密码,字符串
#cmd:执行的命令,列表
def shell_root_exec(ssh_link,sudo,root_passwd,cmd):
    ssh=ssh_link.invoke_shell()
    ssh.send(sudo + '\n')
    try:
        resp = ssh.recv(9999).decode("utf8")
        num = 0
        while '[sudo]' not in resp and '密码' not in resp :
            time.sleep(0.1)
            num +=1
            if num >= 20:
                break
            resp = ssh.recv(9999).decode("utf8")
        if num >=20:
            print('[Failed to raise authority]')
            print('[Timeout 2 seconds to exit or Keyword determination error({})]'.format(resp))
        else:
            # print('[The elevation of authority was successful]')
            print(resp+root_passwd)
            ssh.send(root_passwd+'\n')
            resp = ssh.recv(9999).decode("utf8")
            num = 0
            while '$' not in resp and '#' not in resp:
                time.sleep(0.05)
                num += 1
                if num >= 40:
                    break
                resp = ssh.recv(9999).decode("utf8")
            if num >= 40:
                print('Timeout 2 seconds to exit')
            elif '$' in resp:
                print('[Failed to raise authority]')
            else:
                print(resp)
            for i in cmd:
                ssh.send(i+'\n')
                resp = ssh.recv(9999).decode("utf8")
                num = 0
                while '$' not in resp and '#' not in resp:
                    time.sleep(0.05)
                    num += 1
                    if num >= 40:
                        break
                    resp = ssh.recv(9999).decode("utf8")
                if num >= 40:
                    print('Timeout 2 seconds to exit')
                else:
                    a  = resp.split('\n')[-1]
                    print(a,i)
                    print(resp)
    except Exception as err:
        print(err)
#sudo命令执行
#ssh_link:建立一个sshclient对象,对象
#cmd:命令,字符串类型多个命令之间用;隔开
#root_passwd:root密码,字符串
def shell_ordinary_exec(ssh_link,cmd,root_passwd=''):
    stdin, stdout, stderr = ssh_link.exec_command(cmd, get_pty=True, timeout=300)
    if 'sudo' in cmd:
        stdin.write(root_passwd + '\n')
    try:
        stdout.readlines()
        for out in stdout:
            print(out)
        print('[Execution succeeded] '+cmd)
    except Exception as err:
        print('[Execution failed] ' + cmd)
        print('[ERROR] '+str(err))

#配置文件读取
def Configuration_read():
    try:
        df = pandas.read_excel('./Configuration.xlsx', sheet_name="Sheet1")
        rows = list()
        for index, row in df.iterrows():
            row = list(row)
            row[6]= row[6].split(';')
            rows.append(row)
        return rows
    except Exception as err:
        columns = ['IP','Port','SSH_user','SSH_passwd','sudo','ROOT_passwd','cmd','Getpath','Savepath']
        df = pandas.DataFrame(columns=columns)
        df.to_excel('./Configuration.xlsx', index=False)
        print('The configuration file is missing, the Configuration.xlsx has been regenerated, please modify it and run it')
        exit()
if __name__ == '__main__':
    rows = Configuration_read()
    print(rows)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    for row in rows:
        ssh.connect(row[0], row[1], row[2], row[3])
        # shell_ordinary_exec(ssh,'sudo sh -c "cat /var/log/secure > /home/centos/secure.txt"','centos')#单命令执行
        shell_root_exec(ssh,row[4],row[5],row[6])
        print('Start downloading files from the server[{}]'.format(row[0]))
        scpclient = SCPClient(ssh.get_transport(), sanitize=lambda x: x,socket_timeout=15.0)
        scpclient.get(row[7],row[8],True)
        print('The file download ends')
    input('Press Enter to exit')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值