3

批量执行命令脚本

 2 years ago
source link: https://827607240.github.io/2020/11/03/%E6%89%B9%E9%87%8F%E6%89%A7%E8%A1%8C%E5%91%BD%E4%BB%A4%E8%84%9A%E6%9C%AC/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

批量执行命令脚本

在日常工作中,有很多重复性工作,刚接到任务时没有办法很快的写一个满足实际情况需求的脚本。

找个不忙的时间学习一下,方便下一次使用。

平常也没有写过脚本,这个脚本其实很简单,就是一直不知道怎么写。

后来发现了一个类似的脚本,对该脚本进行改造,完成了我目前的需求。

无交互shell脚本

例子,1.sh

#!/bin/bash
params=${@:2}
for line in `cat $1`
do
 echo "============= {print %s, $line} $params ============="
 ssh $line "$params"
done

这是一个批量远程ssh登录的脚本。里边有我需要的变量元素。

./1.sh ip.txt hostname

第一个变量$1,是一个文件,ip.txt。

第二个变量$params,是一条命令。最好整个命令用双引号引起。


我的需求是从文件中逐个获取一个IP地址执行相同的命令。

#!/bin/bash -e
echo "Usage:testssl-w.sh ip.txt"
for line in `cat $1`
do
 echo "============= {print %s, $line} $params ============="
 bash /home/kali/Desktop/testssl.sh/testssl.sh --quiet -W $line
done
echo "end"

ip.txt文件中的IP可以空格隔开,也可以分行隔开。

我这个脚本只是用了一个变量。虽然比较简单,但还是挺实用的。

bat脚本

先写个简单的试一下,批量ping IP地址的脚本

@echo off
set target=''
for /f %%i in (C:\Users\xxx\Desktop\ip.txt) do (
set target=%%i
ping %%i
)
echo end
pause

这里的ip.txt文件中的IP地址只能一行写一个地址。

到这一步离胜利又进了一步,把命令再改一下就可以了。

之后发现ip.txt不能读到空格后的文本。于是端口信息就添加到命令行中。

本来想着,再加一个变量。但是现在我还不会就先使用这种笨方法吧。起码功能实现了。

@echo off
set target=''
for /f %%i in (C:\Users\xxx\Desktop\ip.txt) do (
set target=%%i
echo py -2 ms12-020_one.py %%i 3389
py -2 ms12-020_one.py %%i 3389
echo py -2 ms12-020_one.py %%i 13389
py -2 ms12-020_one.py %%i 13389
)
echo end
pause

其他类似的脚本基本都可以用这种方式实现了。

win批量新建文件夹

当需要创建大量特定名称的文件夹时。新建文件夹再改名实在是有些繁琐,枯燥。于是找到一个快速新建文件夹的命令。

powershell运行

mkdir $(0..1023 | %{“$_”})

其中0..1023是批量文件夹的序号,表明命名时用的是0~1023的整数,这些数字可以自定义;后面大括号{}里面的内容是序号前的文本,其中字符后面的“$_”指代前面的数字。而在“$_”几个字前也是可以自定义字符的,即如下的命令:

mkdir $(0..1023 | %{“aaaa$_”})

则会新建aaaa0、aaaa1、aaaa2……aaaa1023的文件夹。

从文件中提取出所有的IP地址

Linux:file.txt代表需要提取的文件。ip.txt代表输出的文件。

grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' file.txt > ip.txt

Windows:

type 1.txt | findstr /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"

python脚本:

#coding:utf8
import re
 
f = open('nmap.txt','r')
string = ""
matchIp = re.compile(r'(?<![\.\d])((?:(?:2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(?:2[0-4]\d|25[0-5]|[01]?\d\d?))(?![\.\d])')
matchPort = re.compile(r'\d+/tcp\s+open')
matchSer = re.compile(r'open\s+\w+.+')
for line in f.readlines():
	print line
	m = ''.join(matchIp.findall(line))
	n = ''.join(matchPort.findall(line))[:-4]
	s = ''.join(matchSer.findall(line))[6:]
	if(m <> ''):
		string += "ip:" + m + ' '
	if(n <> ''):
		string += 'port:' + n + ' '
	if(s <> ''):
		string += s + ' '
	if(m <> '' or n <> '' or s <> ''):
		string += '\n'
r = open('r.txt','w')
r.write(string)
r.close()
f.close()

其他的等有用到再更新。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK