summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorSteven Myint <git@stevenmyint.com>2013-10-04 08:14:19 -0700
committerSteven Myint <git@stevenmyint.com>2013-10-04 08:14:19 -0700
commit1cb3226c9d2e57b8ec280433c2ad7c990d63bae0 (patch)
tree87a6f6019ac0d9ee81b3db2b93ac704be458a75c /examples
parentdd0479cb32e55e882a8d1391af2d5b37f25e2db7 (diff)
downloadpexpect-git-1cb3226c9d2e57b8ec280433c2ad7c990d63bae0.tar.gz
Modernize
Diffstat (limited to 'examples')
-rwxr-xr-xexamples/astat.py18
-rwxr-xr-xexamples/bd_client.py6
-rwxr-xr-xexamples/bd_serv.py52
-rwxr-xr-xexamples/chess.py40
-rwxr-xr-xexamples/chess2.py16
-rwxr-xr-xexamples/chess3.py22
-rwxr-xr-xexamples/df.py8
-rwxr-xr-xexamples/ftp.py10
-rwxr-xr-xexamples/hive.py142
-rwxr-xr-xexamples/monitor.py54
-rwxr-xr-xexamples/passmass.py28
-rwxr-xr-xexamples/python.py23
-rwxr-xr-xexamples/rippy.py214
-rwxr-xr-xexamples/script.py26
-rwxr-xr-xexamples/ssh_session.py2
-rwxr-xr-xexamples/ssh_tunnel.py18
-rwxr-xr-xexamples/sshls.py22
-rwxr-xr-xexamples/topip.py54
-rwxr-xr-xexamples/uptime.py8
19 files changed, 417 insertions, 346 deletions
diff --git a/examples/astat.py b/examples/astat.py
index daaffd0..8c9f44e 100755
--- a/examples/astat.py
+++ b/examples/astat.py
@@ -30,13 +30,17 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import os, sys, time, re, getopt, getpass
import traceback
import pexpect, pxssh
def exit_with_usage():
- print globals()['__doc__']
+ print(globals()['__doc__'])
os._exit(1)
def main():
@@ -46,15 +50,15 @@ def main():
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?'])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
- print "Help:"
+ print("Help:")
exit_with_usage()
if '-s' in options:
@@ -79,13 +83,13 @@ def main():
p.expect('([0-9]+\.[0-9]+)\s*requests/sec')
requests_per_second = p.match.groups()[0]
p.logout()
- print requests_per_second
+ print(requests_per_second)
if __name__ == "__main__":
try:
main()
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/bd_client.py b/examples/bd_client.py
index 6bf7e71..8be01f7 100755
--- a/examples/bd_client.py
+++ b/examples/bd_client.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import socket
import sys, time, select
@@ -44,7 +48,7 @@ time.sleep(1)
#s.setblocking(0)
#s.send('COMMAND' + '\x01' + sys.argv[1])
s.send(':sendline ' + sys.argv[2])
-print recv_wrapper(s)
+print(recv_wrapper(s))
s.close()
sys.exit()
#while True:
diff --git a/examples/bd_serv.py b/examples/bd_serv.py
index 1681c2b..d4bb4ea 100755
--- a/examples/bd_serv.py
+++ b/examples/bd_serv.py
@@ -29,6 +29,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
# Having the password on the command line is not a good idea, but
# then this entire project is probably not the most security concious thing
# I've ever built. This should be considered an experimental tool -- at best.
@@ -37,7 +41,7 @@ import time, sys, os, getopt, getpass, traceback, threading, socket
def exit_with_usage(exit_code=1):
- print globals()['__doc__']
+ print(globals()['__doc__'])
os._exit(exit_code)
class roller (threading.Thread):
@@ -116,7 +120,7 @@ def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
- except OSError, e:
+ except OSError as e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
@@ -130,7 +134,7 @@ def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
- except OSError, e:
+ except OSError as e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
@@ -156,8 +160,8 @@ def main ():
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?d', ['help','h','?', 'hostname=', 'username=', 'password=', 'port=', 'watch'])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
command_line_options = dict(optlist)
@@ -183,14 +187,14 @@ def main ():
port = int(options['--port'])
if '--username' in options:
username = options['--username']
- print "Login for %s@%s:%s" % (username, hostname, port)
+ print("Login for %s@%s:%s" % (username, hostname, port))
if '--password' in options:
password = options['--password']
else:
password = getpass.getpass('password: ')
if daemon_mode:
- print "daemonizing server"
+ print("daemonizing server")
daemonize()
#daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log')
@@ -199,7 +203,7 @@ def main ():
virtual_screen = ANSI.ANSI (24,80)
child = pxssh.pxssh()
child.login (hostname, username, password)
- print 'created shell. command line prompt is', child.PROMPT
+ print('created shell. command line prompt is', child.PROMPT)
#child.sendline ('stty -echo')
#child.setecho(False)
virtual_screen.write (child.before)
@@ -209,10 +213,10 @@ def main ():
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
localhost = '127.0.0.1'
s.bind('/tmp/mysock')
- os.chmod('/tmp/mysock',0777)
- print 'Listen'
+ os.chmod('/tmp/mysock',0o777)
+ print('Listen')
s.listen(1)
- print 'Accept'
+ print('Accept')
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#localhost = '127.0.0.1'
#s.bind((localhost, port))
@@ -221,13 +225,13 @@ def main ():
r = roller (0.01, endless_poll, (child, child.PROMPT, virtual_screen))
r.start()
- print "screen poll updater started in background thread"
+ print("screen poll updater started in background thread")
sys.stdout.flush()
try:
while True:
conn, addr = s.accept()
- print 'Connected by', addr
+ print('Connected by', addr)
data = conn.recv(1024)
if data[0]!=':':
cmd = ':sendline'
@@ -262,16 +266,16 @@ def main ():
response.append (shell_window)
#response = add_cursor_blink (response, row, col)
sent = conn.send('\n'.join(response))
- if watch_mode: print '\n'.join(response)
+ if watch_mode: print('\n'.join(response))
if sent < len (response):
- print "Sent is too short. Some data was cut off."
+ print("Sent is too short. Some data was cut off.")
conn.close()
finally:
r.cancel()
- print "cleaning up socket"
+ print("cleaning up socket")
s.close()
if os.path.exists("/tmp/mysock"): os.remove("/tmp/mysock")
- print "done!"
+ print("done!")
def pretty_box (rows, cols, s):
@@ -322,13 +326,13 @@ if __name__ == "__main__":
try:
start_time = time.time()
- print time.asctime()
+ print(time.asctime())
main()
- print time.asctime()
- print "TOTAL TIME IN MINUTES:",
- print (time.time() - start_time) / 60.0
- except Exception, e:
- print str(e)
+ print(time.asctime())
+ print("TOTAL TIME IN MINUTES:", end=' ')
+ print((time.time() - start_time) / 60.0)
+ except Exception as e:
+ print(str(e))
tb_dump = traceback.format_exc()
- print str(tb_dump)
+ print(str(tb_dump))
diff --git a/examples/chess.py b/examples/chess.py
index 47daec2..8e33d9b 100755
--- a/examples/chess.py
+++ b/examples/chess.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import string
import ANSI
@@ -37,11 +41,12 @@ class Chess:
self.child.expect ('Chess')
if self.child.after != 'Chess':
- raise IOError, 'incompatible chess program'
+ raise IOError('incompatible chess program')
self.term.process_list (self.before)
self.term.process_list (self.after)
self.last_computer_move = ''
- def read_until_cursor (self, r,c)
+
+ def read_until_cursor (self, r,c):
while 1:
self.child.read(1, 60)
self.term.process (c)
@@ -56,22 +61,19 @@ class Chess:
return move
def do_move (self, move):
- read_until_cursor (19,60)
- #self.child.expect ('\[19;60H')
+ self.read_until_cursor (19,60)
self.child.sendline (move)
- print 'do_move' move
return move
def get_first_computer_move (self):
self.child.expect ('My move is')
self.child.expect (REGEX_MOVE)
-# print '', self.child.after
return self.child.after
def get_computer_move (self):
- print 'Here'
+ print('Here')
i = self.child.expect (['\[17;59H', '\[17;58H'])
- print i
+ print(i)
if i == 0:
self.child.expect (REGEX_MOVE)
if len(self.child.after) < 4:
@@ -79,7 +81,7 @@ class Chess:
if i == 1:
self.child.expect (REGEX_MOVE_PART)
self.child.after = self.last_computer_move[0] + self.child.after
- print '', self.child.after
+ print('', self.child.after)
self.last_computer_move = self.child.after
return self.child.after
@@ -94,7 +96,7 @@ class Chess:
def quit(self):
self.child.sendline ('quit')
import sys, os
-print 'Starting...'
+print('Starting...')
white = Chess()
white.child.echo = 1
white.child.expect ('Your move is')
@@ -102,17 +104,17 @@ white.set_depth(2)
white.switch()
move_white = white.get_first_computer_move()
-print 'first move white:', move_white
+print('first move white:', move_white)
white.do_move ('e7e5')
move_white = white.get_computer_move()
-print 'move white:', move_white
+print('move white:', move_white)
white.do_move ('f8c5')
move_white = white.get_computer_move()
-print 'move white:', move_white
+print('move white:', move_white)
white.do_move ('b8a6')
move_white = white.get_computer_move()
-print 'move white:', move_white
+print('move white:', move_white)
sys.exit(1)
@@ -124,24 +126,24 @@ white.child.expect ('Your move is')
white.switch()
move_white = white.get_first_computer_move()
-print 'first move white:', move_white
+print('first move white:', move_white)
black.do_first_move (move_white)
move_black = black.get_first_computer_move()
-print 'first move black:', move_black
+print('first move black:', move_black)
white.do_move (move_black)
done = 0
while not done:
move_white = white.get_computer_move()
- print 'move white:', move_white
+ print('move white:', move_white)
black.do_move (move_white)
move_black = black.get_computer_move()
- print 'move black:', move_black
+ print('move black:', move_black)
white.do_move (move_black)
- print 'tail of loop'
+ print('tail of loop')
g.quit()
diff --git a/examples/chess2.py b/examples/chess2.py
index 7fe959a..ae5fcea 100755
--- a/examples/chess2.py
+++ b/examples/chess2.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import string
import ANSI
@@ -49,8 +53,8 @@ class Chess:
while self.term.cur_r != r or self.term.cur_c != c:
try:
k = self.child.read(1, 10)
- except Exception, e:
- print 'EXCEPTION, (r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c)
+ except Exception as e:
+ print('EXCEPTION, (r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
sys.stdout.flush()
self.term.process (k)
fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
@@ -61,7 +65,7 @@ class Chess:
if self.term.cur_r == r and self.term.cur_c == c:
fout.close()
return 1
- print 'DIDNT EVEN HIT.'
+ print('DIDNT EVEN HIT.')
fout.close()
return 1
@@ -106,7 +110,7 @@ class Chess:
return cm
def switch (self):
- print 'switching'
+ print('switching')
self.child.sendline ('switch')
def set_depth (self, depth):
@@ -118,13 +122,13 @@ class Chess:
self.child.sendline ('quit')
def LOG (s):
- print s
+ print(s)
sys.stdout.flush ()
fout = open ('moves.log', 'a')
fout.write (s + '\n')
fout.close()
-print 'Starting...'
+print('Starting...')
black = Chess()
white = Chess()
diff --git a/examples/chess3.py b/examples/chess3.py
index 7c080dd..5080dcb 100755
--- a/examples/chess3.py
+++ b/examples/chess3.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import string
import ANSI
@@ -70,9 +74,9 @@ class Chess:
return move
def get_computer_move (self):
- print 'Here'
+ print('Here')
i = self.child.expect (['\[17;59H', '\[17;58H'])
- print i
+ print(i)
if i == 0:
self.child.expect (REGEX_MOVE)
if len(self.child.after) < 4:
@@ -80,7 +84,7 @@ class Chess:
if i == 1:
self.child.expect (REGEX_MOVE_PART)
self.child.after = self.last_computer_move[0] + self.child.after
- print '', self.child.after
+ print('', self.child.after)
self.last_computer_move = self.child.after
return self.child.after
@@ -95,7 +99,7 @@ class Chess:
def quit(self):
self.child.sendline ('quit')
import sys, os
-print 'Starting...'
+print('Starting...')
white = Chess()
white.do_move('b2b4')
white.read_until_cursor (19,60)
@@ -131,24 +135,24 @@ white.child.expect ('Your move is')
white.switch()
move_white = white.get_first_computer_move()
-print 'first move white:', move_white
+print('first move white:', move_white)
black.do_first_move (move_white)
move_black = black.get_first_computer_move()
-print 'first move black:', move_black
+print('first move black:', move_black)
white.do_move (move_black)
done = 0
while not done:
move_white = white.get_computer_move()
- print 'move white:', move_white
+ print('move white:', move_white)
black.do_move (move_white)
move_black = black.get_computer_move()
- print 'move black:', move_black
+ print('move black:', move_black)
white.do_move (move_black)
- print 'tail of loop'
+ print('tail of loop')
g.quit()
diff --git a/examples/df.py b/examples/df.py
index d565df3..4faa038 100755
--- a/examples/df.py
+++ b/examples/df.py
@@ -26,6 +26,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
child = pexpect.spawn ('df')
@@ -41,7 +45,7 @@ for dummy in range (0, 1000):
break
# Print report
-print
+print()
for m in filesystem_list:
s = "Filesystem %s is at %s%%" % (m[0], m[1])
# highlight filesystems over 95% capacity
@@ -49,5 +53,5 @@ for m in filesystem_list:
s = '! ' + s
else:
s = ' ' + s
- print s
+ print(s)
diff --git a/examples/ftp.py b/examples/ftp.py
index 18e444e..1a4d192 100755
--- a/examples/ftp.py
+++ b/examples/ftp.py
@@ -24,6 +24,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import sys
@@ -50,7 +54,7 @@ child.interact() # Escape character defaults to ^]
# to each other now.
# At this point the script is running again.
-print 'Left interactve mode.'
+print('Left interactve mode.')
# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
@@ -59,7 +63,7 @@ if child.isalive():
child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
- print 'Child did not exit gracefully.'
+ print('Child did not exit gracefully.')
else:
- print 'Child exited gracefully.'
+ print('Child exited gracefully.')
diff --git a/examples/hive.py b/examples/hive.py
index b9ef8c1..ed881ab 100755
--- a/examples/hive.py
+++ b/examples/hive.py
@@ -77,6 +77,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
# TODO add feature to support username:password@host combination
# TODO add feature to log each host output in separate file
@@ -205,7 +209,7 @@ def login (args, cli_username=None, cli_password=None):
hive_connect_info[hostname] = (hostname, username, password, port)
# build up the list of hive connections using the connection information.
for hostname in host_names:
- print 'connecting to', hostname
+ print('connecting to', hostname)
try:
fout = file("log_"+hostname, "w")
hive[hostname] = pxssh.pxssh()
@@ -215,13 +219,13 @@ def login (args, cli_username=None, cli_password=None):
+ " -o 'UserKnownHostsFile /dev/null' ")
hive[hostname].force_password = True
hive[hostname].login(*hive_connect_info[hostname])
- print hive[hostname].before
+ print(hive[hostname].before)
hive[hostname].logfile = fout
- print '- OK'
- except Exception, e:
- print '- ERROR',
- print str(e)
- print 'Skipping', hostname
+ print('- OK')
+ except Exception as e:
+ print('- ERROR', end=' ')
+ print(str(e))
+ print('Skipping', hostname)
hive[hostname] = None
return host_names, hive
@@ -246,36 +250,36 @@ def main ():
synchronous_mode = True
target_hostnames = host_names[:]
- print 'targetting hosts:', ' '.join(target_hostnames)
+ print('targetting hosts:', ' '.join(target_hostnames))
while True:
cmd = raw_input('CMD (? for help) > ')
cmd = cmd.strip()
if cmd=='?' or cmd==':help' or cmd==':h':
- print CMD_HELP
+ print(CMD_HELP)
continue
elif cmd==':refresh':
refresh (hive, target_hostnames, timeout=0.5)
for hostname in target_hostnames:
- print '/' + '=' * (cols - 2)
- print '| ' + hostname
- print '\\' + '-' * (cols - 2)
+ print('/' + '=' * (cols - 2))
+ print('| ' + hostname)
+ print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
- print '# DEAD: %s' % hostname
+ print('# DEAD: %s' % hostname)
else:
- print hive[hostname].before
- print '#' * 79
+ print(hive[hostname].before)
+ print('#' * 79)
continue
elif cmd==':resync':
resync (hive, target_hostnames, timeout=0.5)
for hostname in target_hostnames:
- print '/' + '=' * (cols - 2)
- print '| ' + hostname
- print '\\' + '-' * (cols - 2)
+ print('/' + '=' * (cols - 2))
+ print('| ' + hostname)
+ print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
- print '# DEAD: %s' % hostname
+ print('# DEAD: %s' % hostname)
else:
- print hive[hostname].before
- print '#' * 79
+ print(hive[hostname].before)
+ print('#' * 79)
continue
elif cmd==':sync':
synchronous_mode = True
@@ -289,9 +293,9 @@ def main ():
try:
if hive[hostname] is not None:
hive[hostname].set_unique_prompt()
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
continue
elif cmd[:5] == ':send':
@@ -300,63 +304,63 @@ def main ():
try:
if hive[hostname] is not None:
hive[hostname].send(txt)
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
continue
elif cmd[:3] == ':to':
cmd, hostname, txt = cmd.split(None,2)
- print '/' + '=' * (cols - 2)
- print '| ' + hostname
- print '\\' + '-' * (cols - 2)
+ print('/' + '=' * (cols - 2))
+ print('| ' + hostname)
+ print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
- print '# DEAD: %s' % hostname
+ print('# DEAD: %s' % hostname)
continue
try:
hive[hostname].sendline (txt)
hive[hostname].prompt(timeout=2)
- print hive[hostname].before
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ print(hive[hostname].before)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
continue
elif cmd[:7] == ':expect':
cmd, pattern = cmd.split(None,1)
- print 'looking for', pattern
+ print('looking for', pattern)
try:
for hostname in target_hostnames:
if hive[hostname] is not None:
hive[hostname].expect(pattern)
- print hive[hostname].before
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ print(hive[hostname].before)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
continue
elif cmd[:7] == ':target':
target_hostnames = cmd.split()[1:]
if len(target_hostnames) == 0 or target_hostnames[0] == all:
target_hostnames = host_names[:]
- print 'targetting hosts:', ' '.join(target_hostnames)
+ print('targetting hosts:', ' '.join(target_hostnames))
continue
elif cmd == ':exit' or cmd == ':q' or cmd == ':quit':
break
elif cmd[:8] == ':control' or cmd[:5] == ':ctrl' :
cmd, c = cmd.split(None,1)
if ord(c)-96 < 0 or ord(c)-96 > 255:
- print '/' + '=' * (cols - 2)
- print '| Invalid character. Must be [a-zA-Z], @, [, ], \\, ^, _, or ?'
- print '\\' + '-' * (cols - 2)
+ print('/' + '=' * (cols - 2))
+ print('| Invalid character. Must be [a-zA-Z], @, [, ], \\, ^, _, or ?')
+ print('\\' + '-' * (cols - 2))
continue
for hostname in target_hostnames:
try:
if hive[hostname] is not None:
hive[hostname].sendcontrol(c)
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
continue
elif cmd == ':esc':
@@ -371,9 +375,9 @@ def main ():
try:
if hive[hostname] is not None:
hive[hostname].sendline (cmd)
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
#
@@ -382,19 +386,19 @@ def main ():
if synchronous_mode:
for hostname in target_hostnames:
try:
- print '/' + '=' * (cols - 2)
- print '| ' + hostname
- print '\\' + '-' * (cols - 2)
+ print('/' + '=' * (cols - 2))
+ print('| ' + hostname)
+ print('\\' + '-' * (cols - 2))
if hive[hostname] is None:
- print '# DEAD: %s' % hostname
+ print('# DEAD: %s' % hostname)
else:
hive[hostname].prompt(timeout=2)
- print hive[hostname].before
- except Exception, e:
- print "Had trouble communicating with %s, so removing it from the target list." % hostname
- print str(e)
+ print(hive[hostname].before)
+ except Exception as e:
+ print("Had trouble communicating with %s, so removing it from the target list." % hostname)
+ print(str(e))
hive[hostname] = None
- print '#' * 79
+ print('#' * 79)
def refresh (hive, hive_names, timeout=0.5):
@@ -420,7 +424,7 @@ def resync (hive, hive_names, timeout=2, max_attempts=5):
# TODO This is ideal for threading.
for hostname in hive_names:
if hive[hostname] is not None:
- for attempts in xrange(0, max_attempts):
+ for attempts in range(0, max_attempts):
if not hive[hostname].prompt(timeout=timeout):
break
@@ -451,18 +455,18 @@ if __name__ == '__main__':
(options, args) = parser.parse_args()
if len(args) < 1:
parser.error ('missing argument')
- if options.verbose: print time.asctime()
+ if options.verbose: print(time.asctime())
main()
- if options.verbose: print time.asctime()
- if options.verbose: print 'TOTAL TIME IN MINUTES:',
- if options.verbose: print (time.time() - start_time) / 60.0
+ if options.verbose: print(time.asctime())
+ if options.verbose: print('TOTAL TIME IN MINUTES:', end=' ')
+ if options.verbose: print((time.time() - start_time) / 60.0)
sys.exit(0)
- except KeyboardInterrupt, e: # Ctrl-C
+ except KeyboardInterrupt as e: # Ctrl-C
raise e
- except SystemExit, e: # sys.exit()
+ except SystemExit as e: # sys.exit()
raise e
- except Exception, e:
- print 'ERROR, UNEXPECTED EXCEPTION'
- print str(e)
+ except Exception as e:
+ print('ERROR, UNEXPECTED EXCEPTION')
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/monitor.py b/examples/monitor.py
index b42fc97..a44ebfd 100755
--- a/examples/monitor.py
+++ b/examples/monitor.py
@@ -41,6 +41,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import os, sys, time, re, getopt, getpass
import traceback
import pexpect
@@ -56,7 +60,7 @@ SSH_NEWKEY = '(?i)are you sure you want to continue connecting'
def exit_with_usage():
- print globals()['__doc__']
+ print(globals()['__doc__'])
os._exit(1)
def main():
@@ -67,15 +71,15 @@ def main():
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?'])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
- print "Help:"
+ print("Help:")
exit_with_usage()
if '-s' in options:
@@ -97,9 +101,9 @@ def main():
child = pexpect.spawn('ssh -l %s %s'%(user, host))
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])
if i == 0: # Timeout
- print 'ERROR! could not login with SSH. Here is what SSH said:'
- print child.before, child.after
- print str(child)
+ print('ERROR! could not login with SSH. Here is what SSH said:')
+ print(child.before, child.after)
+ print(str(child))
sys.exit (1)
if i == 1: # In this case SSH does not have the public key cached.
child.sendline ('yes')
@@ -124,24 +128,24 @@ def main():
child.sendline ("PS1='[PEXPECT]\$ '") # In case of sh-style
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
- print "# Couldn't set sh-style prompt -- trying csh-style."
+ print("# Couldn't set sh-style prompt -- trying csh-style.")
child.sendline ("set prompt='[PEXPECT]\$ '")
i = child.expect ([pexpect.TIMEOUT, COMMAND_PROMPT], timeout=10)
if i == 0:
- print "Failed to set command prompt using sh or csh style."
- print "Response was:"
- print child.before
+ print("Failed to set command prompt using sh or csh style.")
+ print("Response was:")
+ print(child.before)
sys.exit (1)
# Now we should be at the command prompt and ready to run some commands.
- print '---------------------------------------'
- print 'Report of commands run on remote host.'
- print '---------------------------------------'
+ print('---------------------------------------')
+ print('Report of commands run on remote host.')
+ print('---------------------------------------')
# Run uname.
child.sendline ('uname -a')
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
if 'linux' in child.before.lower():
LINUX_MODE = 1
else:
@@ -164,36 +168,36 @@ def main():
if 'min' in duration:
child.match = re.search('([0-9]+)\s+min',duration)
mins = str(int(child.match.group(1)))
- print
- print 'Uptime: %s days, %s users, %s (1 min), %s (5 min), %s (15 min)' % (
- duration, users, av1, av5, av15)
+ print()
+ print('Uptime: %s days, %s users, %s (1 min), %s (5 min), %s (15 min)' % (
+ duration, users, av1, av5, av15))
child.expect (COMMAND_PROMPT)
# Run iostat.
child.sendline ('iostat')
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
# Run vmstat.
child.sendline ('vmstat')
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
# Run free.
if LINUX_MODE:
child.sendline ('free') # Linux systems only.
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
# Run df.
child.sendline ('df')
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
# Run lsof.
child.sendline ('lsof')
child.expect (COMMAND_PROMPT)
- print child.before
+ print(child.before)
# # Run netstat
# child.sendline ('netstat')
@@ -219,8 +223,8 @@ if __name__ == "__main__":
try:
main()
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/passmass.py b/examples/passmass.py
index 4c4c850..f5bd04b 100755
--- a/examples/passmass.py
+++ b/examples/passmass.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import sys, getpass
@@ -39,9 +43,9 @@ def login(host, user, password):
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, '[Pp]assword: '])
if i == 0: # Timeout
- print 'ERROR!'
- print 'SSH could not login. Here is what SSH said:'
- print child.before, child.after
+ print('ERROR!')
+ print('SSH could not login. Here is what SSH said:')
+ print(child.before, child.after)
sys.exit (1)
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
@@ -51,7 +55,7 @@ def login(host, user, password):
# the login process is asking for our terminal type.
i = child.expect (['Permission denied', TERMINAL_PROMPT, COMMAND_PROMPT])
if i == 0:
- print 'Permission denied on host:', host
+ print('Permission denied on host:', host)
sys.exit (1)
if i == 1:
child.sendline (TERMINAL_TYPE)
@@ -70,8 +74,8 @@ def change_password(child, user, oldpassword, newpassword):
child.sendline(newpassword)
i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter'])
if i == 0:
- print 'Host did not like new password. Here is what it said...'
- print child.before
+ print('Host did not like new password. Here is what it said...')
+ print(child.before)
child.send (chr(3)) # Ctrl-C
child.sendline('') # This should tell remote passwd command to quit.
return
@@ -80,7 +84,7 @@ def change_password(child, user, oldpassword, newpassword):
def main():
if len(sys.argv) <= 1:
- print USAGE
+ print(USAGE)
return 1
user = raw_input('Username: ')
@@ -88,15 +92,15 @@ def main():
newpassword = getpass.getpass('New Password: ')
newpasswordconfirm = getpass.getpass('Confirm New Password: ')
if newpassword != newpasswordconfirm:
- print 'New Passwords do not match.'
+ print('New Passwords do not match.')
return 1
for host in sys.argv[1:]:
child = login(host, user, password)
if child == None:
- print 'Could not login to host:', host
+ print('Could not login to host:', host)
continue
- print 'Changing password on host:', host
+ print('Changing password on host:', host)
change_password(child, user, password, newpassword)
child.expect(COMMAND_PROMPT)
child.sendline('exit')
@@ -104,5 +108,5 @@ def main():
if __name__ == '__main__':
try:
main()
- except pexpect.ExceptionPexpect, e:
- print str(e)
+ except pexpect.ExceptionPexpect as e:
+ print(str(e))
diff --git a/examples/python.py b/examples/python.py
index c095bec..6fa6ddf 100755
--- a/examples/python.py
+++ b/examples/python.py
@@ -22,20 +22,23 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
# Don't do this unless you like being John Malkovich
# c = pexpect.spawn ('/usr/bin/env python ./python.py')
import pexpect
-c = pexpect.spawn ('/usr/bin/env python')
-c.expect ('>>>')
-print 'And now for something completely different...'
-f = lambda s:s and f(s[1:])+s[0] # Makes a function to reverse a string.
-print f(c.before)
-print 'Yes, it\'s python, but it\'s backwards.'
-print
-print 'Escape character is \'^]\'.'
-print c.after,
+c = pexpect.spawnu('/usr/bin/env python')
+c.expect('>>>')
+print('And now for something completely different...')
+print(''.join(reversed((c.before))))
+print('Yes, it\'s python, but it\'s backwards.')
+print()
+print('Escape character is \'^]\'.')
+print(c.after, end=' ')
c.interact()
c.kill(1)
-print 'is alive:', c.isalive()
+print('is alive:', c.isalive())
diff --git a/examples/rippy.py b/examples/rippy.py
index 25e23e0..07c2c6d 100755
--- a/examples/rippy.py
+++ b/examples/rippy.py
@@ -64,6 +64,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import sys, os, re, math, stat, getopt, traceback, types, time
import pexpect
@@ -218,10 +222,10 @@ def convert (options):
(it is also saved to rippy.conf as text).
'''
if options['subtitle_id'] is not None:
- print "# extract subtitles"
+ print("# extract subtitles")
apply_smart (extract_subtitles, options)
else:
- print "# do not extract subtitles."
+ print("# do not extract subtitles.")
# Optimization
# I really only need to calculate the exact video length if the user
@@ -234,29 +238,29 @@ def convert (options):
# and then calculate the length of that. This is because MP4 video is VBR, so
# you cannot get exact time based on compressed size.
if options['video_length']=='calc':
- print "# extract PCM raw audio to %s" % (options['audio_raw_filename'])
+ print("# extract PCM raw audio to %s" % (options['audio_raw_filename']))
apply_smart (extract_audio, options)
options['video_length'] = apply_smart (get_length, options)
- print "# Length of raw audio file : %d seconds (%0.2f minutes)" % (options['video_length'], float(options['video_length'])/60.0)
+ print("# Length of raw audio file : %d seconds (%0.2f minutes)" % (options['video_length'], float(options['video_length'])/60.0))
if options['video_bitrate']=='calc':
options['video_bitrate'] = options['video_bitrate_overhead'] * apply_smart (calc_video_bitrate, options)
- print "# video bitrate : " + str(options['video_bitrate'])
+ print("# video bitrate : " + str(options['video_bitrate']))
if options['video_crop_area']=='detect':
options['video_crop_area'] = apply_smart (crop_detect, options)
- print "# crop area : " + str(options['video_crop_area'])
- print "# compression estimate"
- print apply_smart (compression_estimate, options)
+ print("# crop area : " + str(options['video_crop_area']))
+ print("# compression estimate")
+ print(apply_smart (compression_estimate, options))
- print "# compress video"
+ print("# compress video")
apply_smart (compress_video, options)
'audio_volume_boost',
- print "# delete temporary files:",
+ print("# delete temporary files:", end=' ')
if options['delete_tmp_files_flag']:
- print "yes"
+ print("yes")
apply_smart (delete_tmp_files, options)
else:
- print "no"
+ print("no")
# Finish by saving options to rippy.conf and
# calclating if final_size is less than target_size.
@@ -267,26 +271,26 @@ def convert (options):
o.append("# revised video_bitrate : %d\n" % revised_bitrate)
for k,v in options.iteritems():
o.append (" %30s : %s\n" % (k, v))
- print '# '.join(o)
+ print('# '.join(o))
fout = open("rippy.conf","wb").write(''.join(o))
- print "# final actual video size = %d" % video_actual_size
+ print("# final actual video size = %d" % video_actual_size)
if options['video_target_size'] != 'none':
if video_actual_size > options['video_target_size']:
- print "# FINAL VIDEO SIZE IS GREATER THAN DESIRED TARGET"
- print "# final video size is %d bytes over target size" % (video_actual_size - options['video_target_size'])
+ print("# FINAL VIDEO SIZE IS GREATER THAN DESIRED TARGET")
+ print("# final video size is %d bytes over target size" % (video_actual_size - options['video_target_size']))
else:
- print "# final video size is %d bytes under target size" % (options['video_target_size'] - video_actual_size)
- print "# If you want to run the entire compression process all over again"
- print "# to get closer to the target video size then trying using a revised"
- print "# video_bitrate of %d" % revised_bitrate
+ print("# final video size is %d bytes under target size" % (options['video_target_size'] - video_actual_size))
+ print("# If you want to run the entire compression process all over again")
+ print("# to get closer to the target video size then trying using a revised")
+ print("# video_bitrate of %d" % revised_bitrate)
return options
##############################################################################
def exit_with_usage(exit_code=1):
- print globals()['__doc__']
- print 'version:', globals()['__version__']
+ print(globals()['__doc__'])
+ print('version:', globals()['__version__'])
sys.stdout.flush()
os._exit(exit_code)
@@ -331,7 +335,7 @@ def input_option (message, default_value="", help=None, level=0, max_level=0):
while 1:
user_input = raw_input (message)
if user_input=='?':
- print help
+ print(help)
elif user_input=='':
return default_value
else:
@@ -347,11 +351,11 @@ def progress_callback (d=None):
def run(cmd):
global GLOBAL_LOGFILE
- print >>GLOBAL_LOGFILE, cmd
+ print(cmd, file=GLOBAL_LOGFILE)
(command_output, exitstatus) = pexpect.run(cmd, events={pexpect.TIMEOUT:progress_callback}, timeout=5, withexitstatus=True, logfile=GLOBAL_LOGFILE)
if exitstatus != 0:
- print "RUN FAILED. RETURNED EXIT STATUS:", exitstatus
- print >>GLOBAL_LOGFILE, "RUN FAILED. RETURNED EXIT STATUS:", exitstatus
+ print("RUN FAILED. RETURNED EXIT STATUS:", exitstatus)
+ print("RUN FAILED. RETURNED EXIT STATUS:", exitstatus, file=GLOBAL_LOGFILE)
return (command_output, exitstatus)
def apply_smart (func, args):
@@ -369,9 +373,9 @@ def apply_smart (func, args):
else:
raise NameError("name '%s' is not defined" % func)
if hasattr(func,'im_func'): # Handle case when func is a class method.
- func = func.im_func
- argcount = func.func_code.co_argcount
- required_args = dict([(k,args.get(k)) for k in func.func_code.co_varnames[:argcount]])
+ func = func.__func__
+ argcount = func.__code__.co_argcount
+ required_args = dict([(k,args.get(k)) for k in func.__code__.co_varnames[:argcount]])
return func(**required_args)
def count_unique (items):
@@ -458,19 +462,19 @@ def extract_audio (video_source_filename, audio_id=128, verbose_flag=0, dry_run_
'''
#cmd = "mplayer %(video_source_filename)s -vc null -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals()
cmd = "mplayer -quiet '%(video_source_filename)s' -vc dummy -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals()
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
def extract_subtitles (video_source_filename, subtitle_id=0, verbose_flag=0, dry_run_flag=0):
'''This extracts the given subtitle_id track as VOBSUB format from the given source video.
'''
cmd = "mencoder -quiet '%(video_source_filename)s' -o /dev/null -nosound -ovc copy -vobsubout subtitles -vobsuboutindex 0 -sid %(subtitle_id)s" % locals()
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
def get_length (audio_raw_filename):
'''This attempts to get the length of the media file (length is time in seconds).
@@ -485,11 +489,11 @@ def get_length (audio_raw_filename):
idl = re.findall("ID_LENGTH=([0-9.]*)", command_output)
idl.sort()
if len(idl) != 1:
- print "ERROR: cannot get length of raw audio file."
- print "command_output of mplayer identify:"
- print command_output
- print "parsed command_output:"
- print str(idl)
+ print("ERROR: cannot get length of raw audio file.")
+ print("command_output of mplayer identify:")
+ print(command_output)
+ print("parsed command_output:")
+ print(str(idl))
return -1
return float(idl[0])
@@ -654,10 +658,10 @@ def compress_video (video_source_filename, video_final_filename, video_target_si
#cmd = "mencoder -quiet '%(video_source_filename)s' -ss 65 -endpos 20 -aid %(audio_id)s -o '%(video_final_filename)s' -ffourcc %(video_fourcc_override)s -ovc lavc -oac lavc %(lavcopts)s %(video_filter)s %(audio_filter)s" % locals()
cmd = build_compression_command (video_source_filename, video_final_filename, video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, seek_skip, seek_length, video_chapter)
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
# If not doing two passes then return early.
if video_encode_passes!='2':
@@ -666,21 +670,21 @@ def compress_video (video_source_filename, video_final_filename, video_target_si
if verbose_flag:
video_actual_size = get_filesize (video_final_filename)
if video_actual_size > video_target_size:
- print "======================================================="
- print "WARNING!"
- print "First pass compression resulted in"
- print "actual file size greater than target size."
- print "Second pass will be too big."
- print "======================================================="
+ print("=======================================================")
+ print("WARNING!")
+ print("First pass compression resulted in")
+ print("actual file size greater than target size.")
+ print("Second pass will be too big.")
+ print("=======================================================")
#
# do the second pass video compression
#
cmd = cmd.replace ('vpass=1', 'vpass=2')
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
return
def compress_audio (audio_raw_filename, audio_compressed_filename, audio_lowpass_filter=None, audio_sample_rate=None, audio_bitrate=None, verbose_flag=0, dry_run_flag=0):
@@ -696,10 +700,10 @@ def compress_audio (audio_raw_filename, audio_compressed_filename, audio_lowpass
if audio_sample_rate:
cmd = cmd + ' --resample ' + audio_sample_rate
cmd = cmd + ' ' + audio_raw_filename + ' ' + audio_compressed_filename
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
(command_output, exitstatus) = run(cmd)
- print
+ print()
if exitstatus != 0:
raise Exception('ERROR: lame failed to compress raw audio file.')
@@ -714,10 +718,10 @@ def mux (video_final_filename, video_transcoded_filename, audio_compressed_filen
def mux_mkv (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag=0, dry_run_flag=0):
'''This is depricated.'''
cmd = 'mkvmerge -o %s --noaudio %s %s' % (video_final_filename, video_transcoded_filename, audio_compressed_filename)
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
def mux_avi (video_final_filename, video_transcoded_filename, audio_compressed_filename, verbose_flag=0, dry_run_flag=0):
'''This is depricated.'''
@@ -732,10 +736,10 @@ def delete_tmp_files (audio_raw_filename, verbose_flag=0, dry_run_flag=0):
global GLOBAL_LOGFILE_NAME
file_list = ' '.join([GLOBAL_LOGFILE_NAME, 'divx2pass.log', audio_raw_filename ])
cmd = 'rm -f ' + file_list
- if verbose_flag: print cmd
+ if verbose_flag: print(cmd)
if not dry_run_flag:
run(cmd)
- print
+ print()
##############################################################################
# This is the interactive Q&A that is used if a conf file was not given.
@@ -744,12 +748,12 @@ def interactive_convert ():
global prompts, prompts_key_order
- print globals()['__doc__']
- print
- print "=============================================="
- print " Enter '?' at any question to get extra help."
- print "=============================================="
- print
+ print(globals()['__doc__'])
+ print()
+ print("==============================================")
+ print(" Enter '?' at any question to get extra help.")
+ print("==============================================")
+ print()
# Ask for the level of options the user wants.
# A lot of code just to print a string!
@@ -776,15 +780,15 @@ def interactive_convert ():
default_id = '128'
if max_prompt_level>=prompts[k][3]:
if len(aid_list) > 1:
- print "This video has more than one audio stream. The following stream audio IDs were found:"
+ print("This video has more than one audio stream. The following stream audio IDs were found:")
for aid in aid_list:
- print " " + aid
+ print(" " + aid)
default_id = aid_list[0]
else:
- print "WARNING!"
- print "Rippy was unable to get the list of audio streams from this video."
- print "If reading directly from a DVD then the DVD device might be busy."
- print "Using a default setting of stream id 128 (main audio on most DVDs)."
+ print("WARNING!")
+ print("Rippy was unable to get the list of audio streams from this video.")
+ print("If reading directly from a DVD then the DVD device might be busy.")
+ print("Using a default setting of stream id 128 (main audio on most DVDs).")
default_id = '128'
options[k] = input_option (prompts[k][1], default_id, prompts[k][2], prompts[k][3], max_prompt_level)
elif k == 'subtitle_id':
@@ -792,15 +796,15 @@ def interactive_convert ():
default_id = 'None'
if max_prompt_level>=prompts[k][3]:
if len(sid_list) > 0:
- print "This video has one or more subtitle streams. The following stream subtitle IDs were found:"
+ print("This video has one or more subtitle streams. The following stream subtitle IDs were found:")
for sid in sid_list:
- print " " + sid
+ print(" " + sid)
#default_id = sid_list[0]
default_id = prompts[k][0]
else:
- print "WARNING!"
- print "Unable to get the list of subtitle streams from this video. It may have none."
- print "Setting default to None."
+ print("WARNING!")
+ print("Unable to get the list of subtitle streams from this video. It may have none.")
+ print("Setting default to None.")
default_id = 'None'
options[k] = input_option (prompts[k][1], default_id, prompts[k][2], prompts[k][3], max_prompt_level)
elif k == 'audio_lowpass_filter':
@@ -823,18 +827,18 @@ def interactive_convert ():
#options['video_final_filename'] = options['video_final_filename'] + "." + options['video_container_format']
- print "=========================================================================="
- print "Ready to Rippy!"
- print
- print "The following options will be used:"
+ print("==========================================================================")
+ print("Ready to Rippy!")
+ print()
+ print("The following options will be used:")
for k,v in options.iteritems():
- print "%27s : %s" % (k, v)
+ print("%27s : %s" % (k, v))
- print
+ print()
c = input_option("Continue?", "Y")
c = c.strip().lower()
if c[0] != 'y':
- print "Exiting..."
+ print("Exiting...")
os._exit(1)
return options
@@ -929,8 +933,8 @@ def clean_options (d):
def main ():
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?', ['help','h','?'])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
command_line_options = dict(optlist)
# There are a million ways to cry for help. These are but a few of them.
@@ -939,18 +943,18 @@ def main ():
missing = check_missing_requirements()
if missing is not None:
- print
- print "=========================================================================="
- print "ERROR!"
- print "Some required external commands are missing."
- print "please install the following packages:"
- print str(missing)
- print "=========================================================================="
- print
+ print()
+ print("==========================================================================")
+ print("ERROR!")
+ print("Some required external commands are missing.")
+ print("please install the following packages:")
+ print(str(missing))
+ print("==========================================================================")
+ print()
c = input_option("Continue?", "Y")
c = c.strip().lower()
if c[0] != 'y':
- print "Exiting..."
+ print("Exiting...")
os._exit(1)
if len(args) > 0:
@@ -962,27 +966,27 @@ def main ():
options = interactive_convert ()
options = clean_options(options)
convert (options)
- print "# Done!"
+ print("# Done!")
if __name__ == "__main__":
try:
start_time = time.time()
- print time.asctime()
+ print(time.asctime())
main()
- print time.asctime()
- print "TOTAL TIME IN MINUTES:",
- print (time.time() - start_time) / 60.0
- except Exception, e:
+ print(time.asctime())
+ print("TOTAL TIME IN MINUTES:", end=' ')
+ print((time.time() - start_time) / 60.0)
+ except Exception as e:
tb_dump = traceback.format_exc()
- print "=========================================================================="
- print "ERROR -- Unexpected exception in script."
- print str(e)
- print str(tb_dump)
- print "=========================================================================="
- print >>GLOBAL_LOGFILE, "=========================================================================="
- print >>GLOBAL_LOGFILE, "ERROR -- Unexpected exception in script."
- print >>GLOBAL_LOGFILE, str(e)
- print >>GLOBAL_LOGFILE, str(tb_dump)
- print >>GLOBAL_LOGFILE, "=========================================================================="
+ print("==========================================================================")
+ print("ERROR -- Unexpected exception in script.")
+ print(str(e))
+ print(str(tb_dump))
+ print("==========================================================================")
+ print("==========================================================================", file=GLOBAL_LOGFILE)
+ print("ERROR -- Unexpected exception in script.", file=GLOBAL_LOGFILE)
+ print(str(e), file=GLOBAL_LOGFILE)
+ print(str(tb_dump), file=GLOBAL_LOGFILE)
+ print("==========================================================================", file=GLOBAL_LOGFILE)
exit_with_usage(3)
diff --git a/examples/script.py b/examples/script.py
index 557fbf1..933b48f 100755
--- a/examples/script.py
+++ b/examples/script.py
@@ -35,6 +35,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import os, sys, time, getopt
import signal, fcntl, termios, struct
import traceback
@@ -44,7 +48,7 @@ global_pexpect_instance = None # Used by signal handler
def exit_with_usage():
- print globals()['__doc__']
+ print(globals()['__doc__'])
os._exit(1)
def main():
@@ -54,15 +58,15 @@ def main():
######################################################################
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?ac:', ['help','h','?'])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
options = dict(optlist)
if len(args) > 1:
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
- print "Help:"
+ print("Help:")
exit_with_usage()
if len(args) == 1:
@@ -70,9 +74,9 @@ def main():
else:
script_filename = "script.log"
if '-a' in options:
- fout = file (script_filename, "ab")
+ fout = open(script_filename, "ab")
else:
- fout = file (script_filename, "wb")
+ fout = open(script_filename, "wb")
if '-c' in options:
command = options['-c']
else:
@@ -90,7 +94,7 @@ def main():
global_pexpect_instance = p
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
- print "Script recording started. Type ^] (ASCII 29) to escape from the script shell."
+ print("Script recording started. Type ^] (ASCII 29) to escape from the script shell.")
p.interact(chr(29))
fout.close()
return 0
@@ -110,11 +114,11 @@ def sigwinch_passthrough (sig, data):
if __name__ == "__main__":
try:
main()
- except SystemExit, e:
+ except SystemExit as e:
raise e
- except Exception, e:
- print "ERROR"
- print str(e)
+ except Exception as e:
+ print("ERROR")
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/ssh_session.py b/examples/ssh_session.py
index 91499ce..f040c5c 100755
--- a/examples/ssh_session.py
+++ b/examples/ssh_session.py
@@ -25,6 +25,8 @@ PEXPECT LICENSE
'''
+from __future__ import absolute_import
+
from pexpect import *
import os, sys
import getpass
diff --git a/examples/ssh_tunnel.py b/examples/ssh_tunnel.py
index 5587f40..03a2e85 100755
--- a/examples/ssh_tunnel.py
+++ b/examples/ssh_tunnel.py
@@ -32,6 +32,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import getpass
import time
@@ -59,8 +63,8 @@ def start_tunnel ():
time.sleep (60) # Cygwin is slow to update process status.
ssh_tunnel.expect (pexpect.EOF)
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
def main ():
@@ -69,15 +73,15 @@ def main ():
time.sleep (1)
index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT])
if index == 2:
- print 'TIMEOUT in ps command...'
- print str(ps)
+ print('TIMEOUT in ps command...')
+ print(str(ps))
time.sleep (13)
if index == 1:
- print time.asctime(),
- print 'restarting tunnel'
+ print(time.asctime(), end=' ')
+ print('restarting tunnel')
start_tunnel ()
time.sleep (11)
- print 'tunnel OK'
+ print('tunnel OK')
else:
# print 'tunnel OK'
time.sleep (7)
diff --git a/examples/sshls.py b/examples/sshls.py
index 731dc6c..4772f8e 100755
--- a/examples/sshls.py
+++ b/examples/sshls.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import getpass, os
@@ -37,18 +41,18 @@ def ssh_command (user, host, password, command):
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
if i == 0: # Timeout
- print 'ERROR!'
- print 'SSH could not login. Here is what SSH said:'
- print child.before, child.after
+ print('ERROR!')
+ print('SSH could not login. Here is what SSH said:')
+ print(child.before, child.after)
return None
if i == 1: # SSH does not have the public key. Just accept it.
child.sendline ('yes')
child.expect ('password: ')
i = child.expect([pexpect.TIMEOUT, 'password: '])
if i == 0: # Timeout
- print 'ERROR!'
- print 'SSH could not login. Here is what SSH said:'
- print child.before, child.after
+ print('ERROR!')
+ print('SSH could not login. Here is what SSH said:')
+ print(child.before, child.after)
return None
child.sendline(password)
return child
@@ -60,14 +64,14 @@ def main ():
password = getpass.getpass('Password: ')
child = ssh_command (user, host, password, '/bin/ls -l')
child.expect(pexpect.EOF)
- print child.before
+ print(child.before)
if __name__ == '__main__':
try:
main()
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/topip.py b/examples/topip.py
index 4f57067..cd9fbc9 100755
--- a/examples/topip.py
+++ b/examples/topip.py
@@ -64,6 +64,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
# See http://pexpect.sourceforge.net/
import pexpect
import pxssh
@@ -83,7 +87,7 @@ TOPIP_LAST_RUN_STATS = '/var/run/topip.last'
def exit_with_usage():
- print globals()['__doc__']
+ print(globals()['__doc__'])
os._exit(1)
def stats(r):
@@ -127,29 +131,29 @@ def main():
try:
optlist, args = getopt.getopt(sys.argv[1:],
'h?valqs:u:p:n:', ['help','h','?','ipv6','stddev='])
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
exit_with_usage()
options = dict(optlist)
munin_flag = False
if len(args) > 0:
if args[0] == 'config':
- print 'graph_title Netstat Connections per IP'
- print 'graph_vlabel Socket connections per IP'
- print 'connections_max.label max'
- print 'connections_max.info Maximum number of connections per IP'
- print 'connections_avg.label avg'
- print 'connections_avg.info Average number of connections per IP'
- print 'connections_stddev.label stddev'
- print 'connections_stddev.info Standard deviation'
+ print('graph_title Netstat Connections per IP')
+ print('graph_vlabel Socket connections per IP')
+ print('connections_max.label max')
+ print('connections_max.info Maximum number of connections per IP')
+ print('connections_avg.label avg')
+ print('connections_avg.info Average number of connections per IP')
+ print('connections_stddev.label stddev')
+ print('connections_stddev.info Standard deviation')
return 0
elif args[0] != '':
- print args, len(args)
+ print(args, len(args))
return 0
exit_with_usage()
if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
- print 'Help:'
+ print('Help:')
exit_with_usage()
if '-s' in options:
hostname = options['-s']
@@ -236,7 +240,7 @@ def main():
# lambda x,y:cmp(x[1], y[1]),reverse=True)
ip_list = ip_list.items()
if len(ip_list) < 1:
- if verbose: print 'Warning: no networks connections worth looking at.'
+ if verbose: print('Warning: no networks connections worth looking at.')
return 0
ip_list.sort(lambda x,y:cmp(y[1],x[1]))
@@ -249,13 +253,13 @@ def main():
# print munin-style or verbose results for the stats.
if munin_flag:
- print 'connections_max.value', s['max']
- print 'connections_avg.value', s['avg']
- print 'connections_stddev.value', s['stddev']
+ print('connections_max.value', s['max'])
+ print('connections_avg.value', s['avg'])
+ print('connections_stddev.value', s['stddev'])
return 0
if verbose:
pprint (s)
- print
+ print()
pprint (ip_list[0:average_n])
# load the stats from the last run.
@@ -266,13 +270,13 @@ def main():
if ( s['maxip'][1] > (s['stddev'] * stddev_trigger)
and s['maxip']==last_stats['maxip'] ):
- if verbose: print 'The maxip has been above trigger for two consecutive samples.'
+ if verbose: print('The maxip has been above trigger for two consecutive samples.')
if alert_flag:
- if verbose: print 'SENDING ALERT EMAIL'
+ if verbose: print('SENDING ALERT EMAIL')
send_alert(str(s), 'ALERT on %s'
% hostname, alert_addr_from, alert_addr_to)
if log_flag:
- if verbose: print 'LOGGING THIS EVENT'
+ if verbose: print('LOGGING THIS EVENT')
fout = file(TOPIP_LOG_FILE,'a')
#dts = time.strftime('%Y:%m:%d:%H:%M:%S', time.localtime())
dts = time.asctime()
@@ -283,7 +287,7 @@ def main():
# save state to TOPIP_LAST_RUN_STATS
try:
pickle.dump(s, file(TOPIP_LAST_RUN_STATS,'w'))
- os.chmod (TOPIP_LAST_RUN_STATS, 0664)
+ os.chmod (TOPIP_LAST_RUN_STATS, 0o664)
except:
pass
# p.logout()
@@ -292,10 +296,10 @@ if __name__ == '__main__':
try:
main()
sys.exit(0)
- except SystemExit, e:
+ except SystemExit as e:
raise e
- except Exception, e:
- print str(e)
+ except Exception as e:
+ print(str(e))
traceback.print_exc()
os._exit(1)
diff --git a/examples/uptime.py b/examples/uptime.py
index 3316600..3187a56 100755
--- a/examples/uptime.py
+++ b/examples/uptime.py
@@ -22,6 +22,10 @@ PEXPECT LICENSE
'''
+from __future__ import print_function
+
+from __future__ import absolute_import
+
import pexpect
import re
@@ -68,6 +72,6 @@ if 'min' in duration:
mins = str(int(p.match.group(1)))
# Print the parsed fields in CSV format.
-print 'days, hours, minutes, users, cpu avg 1 min, cpu avg 5 min, cpu avg 15 min'
-print '%s, %s, %s, %s, %s, %s, %s' % (days, hours, mins, users, av1, av5, av15)
+print('days, hours, minutes, users, cpu avg 1 min, cpu avg 5 min, cpu avg 15 min')
+print('%s, %s, %s, %s, %s, %s, %s' % (days, hours, mins, users, av1, av5, av15))