自动创建samba目录的shell脚本

1 shell脚本实现ssh自动登录远程服务器

spawn 开启一个子进程
expect 预期收到的字符
send 发送字符
interact 交互

#!/usr/bin/expect
spawn ssh [email protected]
expect "*password:"
send "123\r"
expect "*#"
interact

2 如何向expect脚本传递参数

expect是通过set <变量名称> [lindex argv 0]

#!/usr/bin/expect
set timeout 10
set username [lindex $argv 0]
set password [lindex $argv 1]
set hostname [lindex $argv 2]
spawn ssh-copy-id -i .ssh/id_rsa.pub $username@$hostname
expect "yes/no"
send "yes\r"
expect "password:"
send "$password\r"

expect eof

3 如何解决echo时重定向到文件时permission denied

加一个“ sh -c ”就可以把权限指定到整条shell了。如:
sudo sh -c "echo '[yaf]' > /usr/local/php/etc/include/yaf.ini"
另一种方法是利用管道和 tee 命令,该命令可以从标准输入中读入信息并将其写入标准输出或文件中,tee 命令de “-a” 选项的作用等同于 “>>” 命令,如:
echo “xxxx” | sudo tee -a test.txt

4 脚本示例

#!/usr/bin/expect

set HostIp [lindex $argv 0]
set UserId [lindex $argv 1]
set UserPwd [lindex $argv 2]
set new_smb_folder [lindex $argv 3]
set path_of_samba [lindex $argv 4]

set timeout -1
spawn ssh $UserId@$HostIp
expect "*?password:" { send "$UserPwd\r"}

expect "$ " { send "sudo mkdir -p '$path_of_samba'\r" }
expect ": " { send "$UserPwd\r" }
expect "$ " { send "echo -e '$new_smb_folder' | sudo tee -a /etc/samba/smb.conf\r"}
expect "$ " { send "sudo service smbd restart\r" }

调用:

full_string="
[$name_of_sambaRoot]
  path = $path_of_sambaRoot
  available = yes
  browseable = yes
  public = yes
  writable = yes
"
./enableSamba.expect "$ipAddress" "$UserId" "$UserPwd" "$full_string" "$path_of_sambaRoot"

5 脚本示例,写成脚本用expect -f script.sh执行

echo "spawn scp auto_operation_remote.sh $l_user@$l_machine_ip:/tmp/
    expect \"*want to continue connecting (yes/no)*\" {send \"yes\r\"}
    expect \"*password*\" {send \"$l_rsync_sudo_pwd\r\"}
    expect eof" > temp.sh
expect -f temp.sh > rsync_error_tmp.log

常见错误:
expect: spawn id exp5 not open
while executing
"expect "password" {send "123456\r"}"
(file "temp.sh" line 3)
原因:特定的机器上,因为之前已经ssh_key加入信任,因此scp操作不需要输入密码。

你可能感兴趣的:(自动创建samba目录的shell脚本)