自動建立samba目錄的shell指令碼

weixin_34321977發表於2017-12-26

1 shell指令碼實現ssh自動登入遠端伺服器

spawn 開啟一個子程式
expect 預期收到的字元
send 傳送字元
interact 互動

#!/usr/bin/expect
spawn ssh root@192.168.22.194
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操作不需要輸入密碼。

相關文章