如何批量在多台服务器上执行命令

在一些场景里,我们可能需要同时在多台服务器上执行命令,如果一台台登录服务器执行嘛,这效率未免太低了。

有没有什么比较简单的方式,可以实现批量在多台服务器上执行命令呢。


场景1:MSF批量执行命令

从攻击者的角度来说,通过MSF获取到了多个session,如何批量在这些服务器上执行命令?

批量执行meterpreter命令

session -C “命令”

批量执行cmd命令

session -c “命令”

 

场景2:Windows服务器批量执行命令

在Windows中有很多种方式可以实现横向移动,通过系统自带命令或工具可以实现。但如果我们需要在多台服务器上执行命令,有没有一种比较简洁的方式?

PsExec一行命令就可以实现:

PsExec.exe @file -u administrator -p  xxxx  -s -i -c 1.bat

如上,PsExec将在file文件中列出的每台计算机上执行1.bat的内容。

场景3:Linux服务器批量执行命令

在Linux自动化运维里,有很多类似的工具,可以实现批量命令执行,如Ansible、SaltStack、Fabric、Puppet、Chef等。

这里介绍两种简单的方式,通过编写shell/python脚本快速实现批量命令执行。

(1)使用expect批量自动登录服务器并执行命令

#!/bin/bash
cat iplist|while read line #iplist文件中存放了IP地址和密码,每行格式为“IP地址 密码”
do
    a=($line)                    
    /usr/bin/expect <<EOF       
    spawn ssh root@${a[0]}     
    expect {
    "*yes/no" { send "yes\r"; exp_continue}
    "*password:" { send "${a[1]}\r" } 
    }
    expect "#"
    send "whoami\r"
    send "ip add\r"                
    send "exit\r"           
    expect eof
    EOF
done

 

(2)使用Fabric工具实现批量命令执行

Fabric是一个使用python编写的自动化运维工具,我们可以通过这个工具来编写脚本实现很多功能。

from fabric.api import *

hosts=['10.1.1.221','10.1.1.132']
env.user='root'
env.password = 'abc123!'
def host_type():
    run('uname -r')
    sudo("cd /tmp;touch 1.txt") 
    run('ls /tmp')

for host in hosts:
    env.host_string = host
    try:
        host_type()
    except:
        pass

posted @ 2021-03-05 19:37  Bypass  阅读(2816)  评论(0编辑  收藏  举报