shell学习--自定义Linux指令调用shell脚本实现远程登录与拷贝

一、远程登录指令实现

1、在home下面创建文件夹my_sh,把脚本都放在这个文件夹下

mkdir my_sh

cd my_sh

2、编写远程登录的expect脚本

vi my_ssh.sh

 #!/usr/bin/expect
 set ip [lindex $argv 0]
 set pw [lindex $argv 1]
 #spawn ssh -p $ip xxx@xxx
 spawn ssh xxx@$ip
 expect {
 "*yes/no" {send "yes\r"; exp_continue}
 "*password:" {send "$pw\r"}
 "*refused" {send "exit\r"}
 }
 interact

这个脚本需要获取两个参数,一个是ip地址,一个是password

3、编写调用上述脚本my_ssh.sh的bash脚本

vi ssh.sh

#!/bin/bash
A=$1;

if [ ! -n "$1" ];
then {
 echo "no portnum"
 exit
}
fi

#B=c${A#*160}
B=$2

~/my_sh/my_ssh.sh $A $B

这个脚本需要需要传入两个参数,一个是ip地址,一个是password,并且调用另外一个脚本

4、修改~/.bashrc文件,添加指令my_ssh,以便任何情况下打开终端都能够使用这个指令

vi ~/.bashrc

在最后添加

alias my_ssh='~/my_sh/ssh.sh'

二、远程拷贝指令和上面流程完全一样,代码如下

my_scp.sh

#!/usr/bin/expect
set ip [lindex $argv 0]
set pwd [lindex $argv 1]
set sou_dir [lindex $argv 2]
set dis_dir [lindex $argv 3]
#spawn scp -P $ip xxx@xxx:$sou_dir $dis_dir
spawn scp xxx@$ip:$sou_dir $dis_dir
expect {
"*yes/no" {send "yes\r"; exp_continue}
"*password:" {send "$pwd\r"}
"*refused" {send "exit\r"}
}
interact
                              

scp.sh

#!/bin/bash
A=$1

if [ ! -n "$1" ]
then {
  echo "no portnum"
  exit
}
fi
 
B=c${A#*160}
 
C=$2
if [ ! -n "$2" ]
then
 {
    echo "no source dir"
    exit
}
fi
 
D=$3
if [ ! -n "$3" ]
then
{
    echo "no dist dir, default current dir"
    D="./"
}
fi


~/my_sh/my_scp.sh $A $B $C $D

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章