BASH scripting for username/password constructs

我的未来我决定 提交于 2020-02-05 01:53:26

问题


I want to write a simple bash script using ncat to open a connection to a ISP and its port.

The first command would be:

nc address port

Upon doing this, I am prompted first to provide a username. I must hit ENTER, and then I will be prompted to provide a password and then I must hit ENTER again.

After this, I want to open a Terminal process window. Can anyone point me to sufficient resources for this type of scripting?

I know the username and password already, but I'm not too sure how to work around the fact that I must provide it and then hit enter. I'm also unsure how to open a new Terminal proceses.

Thanks in advance!


回答1:


Check out expect script Expect

Example:

# Assume $remote_server, $my_user_id, $my_password, and $my_command were read in earlier
# in the script.
# Open a telnet session to a remote server, and wait for a username prompt.
spawn telnet $remote_server
expect "username:"
# Send the username, and then wait for a password prompt.
send "$my_user_id\r"
expect "password:"
# Send the password, and then wait for a shell prompt.
send "$my_password\r"
expect "%"
# Send the prebuilt command, and then wait for another shell prompt.
send "$my_command\r"
expect "%"
# Capture the results of the command into a variable. This can be displayed, or written to disk.
set results $expect_out(buffer)
# Exit the telnet session, and wait for a special end-of-file character.
send "exit\r"
expect eof



回答2:


The secret lies in the HEREDOC

You can solve this problem with something akin to:

$ command-that-needs-input <<EOF
authenticate here
issue a command
issue another command
EOF

Look at the link I provided for here documents - it includes support for variable substitution and lots of other useful things. Enjoy!



来源:https://stackoverflow.com/questions/15373366/bash-scripting-for-username-password-constructs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!