当前位置:网站首页>Script design for automatic login and command return

Script design for automatic login and command return

2022-06-24 16:15:00 mariolu

Before the holiday, we were inspecting the health of the machine , You will need to use a batch script . For example, it is common to execute commands in batches for a bunch of online physical machines , View process health status , Is there any setting crontab Monitor auto pull script , Are there any exceptions in the log .

The dumbest way is to go one by one ip Log in to perform these operations . But if there are dozens of machines on the platform , So it is not very realistic to do manual work in batches . So we usually have the following methods .

One 、 Use polysh:

Polysh( Formerly known as Group Shell or gsh) It's a remote Shell multiplexer . It can be in a shell The program controls multiple remote devices at a time shell Program . Unlike other command schedulers , It's interactive , The interface looks like the following .

Two 、 Use ssh Carry out orders , And then use while Cycle batch execution and recycle results

But in general ssh Considering safety , It will be designed that the password must be entered manually , So here's another one sshpass Auxiliary input password .

sshpass -p [your password] ssh [user]@[your ip] [your shell command]

Notice that many machines log in for the first time , There is no trust that generates credentials and places them locally host In the list .

So you need to add the ignore option -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no , Otherwise, automatic login will fail .

-t Option is to force the assignment of pseudo terminals .

such sshpass It can deliver ssh A password , And then let ssh Sign in

2.1 Batch file

Suppose we have a file now [ip list file] There is a pair of ip list , A line of one ip. Then you can use while Loop processing .

while read line; do sshpass -p [your password] ssh -t -no UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no [user]@"$line" [your command]; done < [ip list file]

Notice here ssh With one -n Options ,ssh Because it reads by default stdin.

-n Give Way / dev / null Redirect to stdin( actually , Prevent reading from standard input ). It has to be added here -n, or while It will only cycle once and exit .

原网站

版权声明
本文为[mariolu]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/05/20210501132816424y.html