Search code examples
linuxshelltelnetputty

"telnet" command fails with "bad port" when executed in shell script, but works on command prompt


This is probably really simple. I am logging into a remote server using PuTTY and running a telnet 12.34.56.789 22 command to test TCP connections on port 22.

This works fine when I type the command manually, but I have a range of destinations to check and I thought it would be better to use a script for this. I created a very basic shell script which is just a list of the commands I want to run one after another. When I run this script from PuTTY I get an error saying

: bad port

Can anyone explain to me why the command works when I type it manually, but produces an error when I run the script?

Script:

telnet 10.52.33.46 22  
telnet 10.52.33.47 22  
telnet 10.52.33.48 22  
telnet 10.52.33.49 22  
telnet 10.52.33.50 22  
telnet 10.52.33.51 22  
telnet 10.52.33.52 22  
telnet 10.52.33.53 22  
telnet 10.52.33.54 22  
telnet 10.52.33.55 22

Here is a screenshot of the PuTTY window with the error message. I save the above script (159999.sh) onto the host server, then run it from there.

Here is some of the commands running after I type them manually (in this case they are supposed to fail to connect)


Solution

  • Your script file has Windows CR/LF line endings, while *nix systems use LF only.

    The additional CR is taken as a part of the telnet command, particularly as a part of the last "port" argument. Hence the "bad port" error.

    Make sure you either: