search

Home  >  Q&A  >  body text

Linux 怎麼用Shell腳本來執行su - 並且輸入密碼得到root權限

如題,我怎麼一行命令執行 su - 並且輸入密碼得到root權限

下面這樣不行

$ echo "mypassword" | su -
su: Sorry
PHP中文网PHP中文网2785 days ago716

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-17 14:35:25

    Can use expect script

    #!/usr/bin/env expect
    
    spawn su
    
    expect "Password:"
    
    send "Your Password\r" # 不要丢了 '\r'
    
    interact

    reply
    0
  • PHPz

    PHPz2017-04-17 14:35:25

    echo "password" | sudo -S try

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:35:25

    This is not possible and should not be done. Consider that if privileges can be escalated in this way, the root privileges of the system will be accessible to anyone.

    Generally, if a script requires root permissions, we will execute the script directly as root at the beginning, instead of running it as our own ID first, and then switch identities through su or sudo during an operation that requires permissions. .

    In addition, if you need to execute it as root and it can be executed and called by a user with ordinary permissions, you can consider setting setuid for the execution file

    reply
    0
  • Cancelreply