A surprise I found out recently is that Bash natively supports tcp connections as file descriptors. To use:
exec 6<>/dev/tcp/ip.addr.of.server/445
echo -e "GET / HTTP/1.0
" >&6
cat <&6
I'm using 6 as the file descriptor because 0,1,2 are stdin, stdout, and stderr. 5 is sometimes used by Bash for child processes, so 3,4,6,7,8, and 9 should be safe.
As per the comment below, to test for listening on a local server in a script:
exec 6<>/dev/tcp/127.0.0.1/445 || echo "No one is listening!"
exec 6>&- # close output connection
exec 6<&- # close input connection
To determine if someone is listening, attempt to connect by loopback. If it fails, then the port is closed or we aren't allowed access. Afterwards, close the connection.
Modify this for your use case, such as sending an email, exiting the script on failure, or starting the required service.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…