系统:Windows10、Ubuntu版WSL(Windows Subsystem for Linux)
工具:Windows Terminal (Preview)
因不想使用xhell、putty等软件,故折腾脚本以便登录服务器管理.
将会介绍3个shell脚本用于登录服务器.
0x00
Ubuntu需要安装依赖包
1 | sudo apt-get install expect |
脚本编写
1 | touch server-ONE.sh |
脚本内容
server-ONE.sh
1 | !/usr/bin/expect -f |
脚本权限
确定server-ONE.sh脚本有可执行权限
1 | chmod +x server-ONE.sh |
执行server-ONE.sh脚本
./server-ONE.sh
第二种给脚本有可执行权限
1 | chmod 777 ./server-ONE.sh |
注意
不能按照习惯来用sh server-ONE.sh来这行expect的程序,会提示找不到命令,如下:1
2
3
4server-ONE.sh: line 3: spawn: command not found
couldn't read file "*password:": no such file or directory
server-ONE.sh: line 5: send: command not found
server-ONE.sh: line 6: interact: command not found
因为expect用的不是bash所以会报错。因为bash和expect的脚本指定了不同的脚本解释器1
2!/usr/bin/expect -f
!/bin/bash
故而执行的时候直接./server-ONE.sh
0x01
需要两个文件,loginserver.sh用于登录,serverList.txt服务器列表信息。
脚本编写
loginserver.sh,脚本读取serverList.txt文件,serverList.txt文件存有服务器信息.1
2touch loginserver.sh
vim loginserver.sh
脚本内容
loginserver.sh1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46!/bin/bash
ReferenceLink:https://yq.aliyun.com/articles/516347
show all host infos of serverList.txt
if [[ -f ./serverList.txt ]]
then
hostNum=`cat ./serverList.txt | wc -l`
else
echo "No .serverList.txt in ./ dir, please create it and add server infos."
exit
fi
while [ True ]
do
echo -e "+++++++++++ Host List ++++++++++++++++"
awk -F' ' '{printf("%3d -> %s@%s\n", NR,$1,$2)}' ./serverList.txt
echo -e "++++++++++++++++++++++++++++++++++++++"
echo -e "Enter hostID at first column."
echo -e "Enter q or Q to quit."
read hostID
if [[ "$hostID" == 'q' ]] || [[ "$hostID" == 'Q' ]]
then
exit
elif [[ $hostID -lt 1 ]] || [[ $hostID -gt $hostNum ]]
then
echo "Wrong hostID is selected, Only $hostNum hosts are listed, please check."
continue
else
break
fi
done
user=""
host=""
passwd=""
eval $(awk -v hostID=$hostID -F' ' '{if (NR==hostID) {printf("user=%s;host=%s;passwd=%s;",$1,$2,$3);}}' ./serverList.txt)
echo $user, $host, $passwd
echo "login in $user@$host"
expect -c "
set timeout 30
spawn ssh $user@$host
expect {
\"*yes/no\" { send \"yes\r\"; exp_continue }
\"*?assword:\" { send \"$passwd\r\" }
}
interact
"
server列表
第一列:系统用户名称;第二列:服务器ip地址;第三列:服务器密码。1
2touch serverList.txt
vim serverList.txt
serverList.txt1
2
3test 192.168.1.10 123456
test 192.168.1.11 123456
test 192.168.1.12 123456
执行
1 | bash loginserver.sh |
0x02
需要两个文件,managerserver.sh用于登录,managerserver.txt服务器列表信息。
脚本编写
managerserver.sh,脚本读取managerserver.txt文件,managerserver.txt文件存有服务器信息.
1 | touch managerserver.sh |
脚本内容
managerserver.sh
1 | !/bin/bash |
server列表
第一列:服务器名称;第二列:系统用户名;第三列:服务器ip地址;第四列:服务器密码。1
2touch managerserver.txt
vim managerserver.txt
managerserver.txt1
2
3server-ONE test 192.168.1.10 123456
server-TWO test 192.168.1.11 123456
server-THREE test 192.168.1.12 123456
执行
1 | bash managerserver.sh |