使用指令碼切換使用者執行命令

2021-10-03 07:48:06 字數 944 閱讀 3068

需要使用到spawn 和 expect 命令,可以是expect指令碼或者sh指令碼

相關參考:

1

--test.expect

#!/usr/bin/expect

spawn su gw04

expect "password:"

send "gw123\n"

send "sudo ifconfig can0 down\n"

send "gw123\n"

interact

#expect eof

#exit

2-- test1.sh

#!/usr/bin/expect

spawn su gw04

expect "password:"

send "gw123\n"

send "sudo ifconfig can0 down\n"

send "gw123\n"

interact

#expect eof

#exit

2--test2.sh

#!/bin/sh

expect -c "

spawn su - gw04

expect \"password:\"

send \"gw123\r\"

send \" sudo ifconfig can0 up \r\"

send \"gw123\r\"

interact

"

執行這寫檔案

--interact   //停留在遠端機器上不退出來  

--expect eof 停留在遠端機器上一會兒再退出

expect test.expect

expect test1.sh

bash test2.sh

shell指令碼裡切換使用者執行命令

用當前使用者 如root 執行乙個指令碼,在指令碼中需要切換到其他使用者去 如ossadm 執行某條命令 直接在指令碼裡進行su ossadm 或者su ossadm是行不通的,不管如何環境變數等一些東西比較容易混亂,載入不到對應使用者的環境變數 有兩種方式可以在指令碼裡進行切換 1,使用eof b...

Shell指令碼中實現切換使用者並執行命令操作

今天公司同事來找到我說要在伺服器上用另外乙個使用者執行python指令碼,但設定到crontab裡卻老是root使用者來執行,為了省事我就想了乙個偷懶的辦法,就是用shell指令碼切換到那個使用者,然後去執行那個python指令碼.好了,這篇文章我只演示怎麼用shell程式設計客棧指令碼切換到其他使...

切換使用者命令 su sudo

使用root使用者登入可能會由於人為的誤操作導致資料丟失。通用做法是使用普通使用者登入並使用系統,當需要執行管理操作時,再切換到root使用者執行管理操作。臨時切換使用者命令su su root password 普通使用者切換到root使用者時,需要輸入root使用者密碼 root使用者切換到普通...