I'm using Python's telnetlib.write() function for quite some time without issues, but in this case the command that I want to send does nothing. While the same command sent through SecureCRT works fine.
Here's more or less what I have:
import telnetlib
tn = telnetlib.Telnet(HOST)
tn.read_until('login: ')
tn.write(user + '\n')
if pswrd:
tn.read_until('Password: ')
tn.write(pswrd + '\n')
tn.write('echo "" > /path/to/file.log' + '\n')
tn.write('exit\n')
tn.close()
What this should do is clear the contents of file.log, but the file remains the same. Why is this happening? If it's worth mentioning, the telnet server is running SunOS. Thanks!
Your problem is almost certainly a timing error.
Without being able to debug it, or seeing the results of you debugging it, it's hard to be sure exactly what the problem is, but my guess is something like this:
The SunOS machine's telnetd
server has a relatively small buffer, say 16 bytes. So, if you send it that whole command before the shell has started, it's only going to send 16 bytes of it to the shell. Which will, of course, not do what you want. But if you wait until the shell has started, it'll get the whole command, and therefore work.
By adding tn_setdebuglevel(1)
to your program, you're changing the timing—the extra time it takes to print out the debugging information is just enough to (usually) give the shell time to start before you've filled up the buffer, so it happens to work.
The password prompt probably has the same problem, which you solved by using `tn.read_until('Password: '). You just need to do the same thing here. For example (depending on what the expected prompt is):
# ...
tn.read_until('$')
tn.write('echo "" > /path/to/file.log\n')
tn.read_until('$')
tn.write('exit\n')
tn.close()