shell脚本

which bash 查看bash 的安装路径


图片.png

1创建shell 脚本文件

touch ip.sh
#!/bin/bash                 声明( 必须写在shell 脚本的第一行)
#----------------
#备注:
#script funtion is scan live host ip
# writer name is ttgo2
#-----------------


赋予 shell 脚本 执行权限

chmod +x ip.sh
脚本 执行前可以先 进行调试

bash -x t.sh  调试脚本

解决expect实现单台、多台服务器批量scp传输文件的问题

1 单台传输

ip.sh (shell脚本)

#!/bin/bash
#------------------
name=$1         #接收第一个位置参数
passwd=$2
ip=$3
file=$4
./scp.exp $name $passwd $ip $file  #调用scp.exp 脚本

scp.exp (expect 脚本)

#!/usr/bin/expect
set timeout 20

set username [lindex $argv 0]     #接收参数
set passwd [lindex $argv 1]
set host [lindex $argv 2]
set src_file [lindex $argv 3]
spawn scp -r $src_file $username@$host:/tmp/      #spawn 执行shell 脚本的命令

expect {
      "(yes/no)?"
          {
              send "yes\r"
              expect "password:" { send "$passwd\n" }
           }
       "password:" 
           {
                send "$passwd\n"
           }
        }

expect "100%"
expect eof

执行前 赋予 文件执行权限 chmod +x ip.sh

执行 ./ip.sh 脚本就可以向目标主机传文件了 (别忘了传参 例: ./ip.sh root 123 10.66.8.56 test.txt)

2 多台传输

首先创建一个存放 ip name password (file path)
也可以用 nmap -sn 扫描存活主机 并将扫描结果 导入文件

这里我 只创建一个 server_list.conf 文件存放要 传给的目标

lmt 7890 10.22.9.41 test.txt   #(test.txt 在当前文件夹下  如果在其它地方记得写绝对路径)
liuxq root 10.22.9.21 test.txt

test.sh (创建一个shell 脚本 读入 server_list.conf 文件 并执行ip.sh脚本 ip.sh 再调用scp.exp )

备注 ip.sh 和 scp.exp 和单台传输 是一样的

#!/bin/bash
host_list="server_list.conf"
cat $host_list | while read line  #一次读 一行
do
    username=`echo $line|awk '{print $1}'`
    password=`echo $line|awk '{print $2}'`
    host_ip=`echo $line|awk '{print $3}'`
        src_file=`echo $line|awk '{print $4}'`

./ip.sh $username $password $host_ip $src_file

done
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容