import telnetlib
import os
import re
current_dir = os.getcwd()
IP = <IP>
def login_as_root():
print "logging in as root..."
tn.read_until("login: ")
tn.write("root\r")
response = tn.expect([re.compile(b"Password:"),b"root#",])
if "Password:" in response[2]:
send_msg("root", "root#")
else:
print "logging without passwd"
def send_msg(msg, wait_str, print_msg=0):
if print_msg:
print msg
tn.write("%s\n" % msg)
return tn.read_until(wait_str)
def launch_update():
try:
print send_msg("mount -o remount,rw /", "root# ", print_msg=1)
except:
Exception("Update configuring is failed")
def main():
global tn
try:
tn = telnetlib.Telnet(IP)
login_as_root()
except:
raise Exception("Connect failed")
launch_update()
if __name__ == "__main__":
main()
Need help with login_as_root(). There are 2 cases to login as root: with password and without any password. I have to connect correctly to host and then launch several commands in launch_update(). Script stucks after mount command.
Related
So, I'm a beginner with Python and I'm mostly building an SSH client for fun and working on a little automation for repetitive tasks at work. The script works as intended right now except for one minor annoyance - the entered command shows up twice in command prompt and powershell (but for some reason it doesn't when running the script in Pycharm)
CMD response:
FortiGate-60F # sh sys admin
sh sys admin
config system admin
edit "admin"
set accprofile "super_admin"
set vdom "root"
next
end
PyCharm response:
FortiGate-60F # sh sys admin
config system admin
edit "admin"
set accprofile "super_admin"
set vdom "root"
next
end
Full script (un/pw redacted):
import paramiko
import time
import sys
import colorama
colorama.init()
def shell(chan):
import threading
def writeall(sock):
decoder = ""
while True:
data = sock.recv(256)
decoder = str(data.decode("utf8", "ignore"))
if not data:
sys.stdout.write("\r\n*** DISCONNECTED ***\r\n\r\n")
sys.stdout.flush()
remote_conn.close()
sys.exit()
sys.stdout.write(decoder)
sys.stdout.flush()
if "Type the hot key to suspend the connection: <CTRL>Z" in decoder:
sys.stdout.write(f"\r\033[1F\033[2KType the hot key to suspend the connection: <CTRL>C\n\n")
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.readline()
if d == "set_phone_home\n":
chan.send("\rexec batch start\n")
time.sleep(.5)
chan.send("config system central-management\n")
time.sleep(.5)
chan.send("set type fortimanager\n")
time.sleep(.5)
chan.send("set serial-number \"FMG-VM0A16000497\"\n")
time.sleep(.5)
chan.send("set fmg \"172.85.135.226\"\n")
time.sleep(.5)
chan.send("end\n")
time.sleep(.5)
chan.send("exec batch end\n")
elif d == "firmware_up\n":
chan.send("\rexecute restore image usb image.out\n")
sys.stdout.write("\033[F")
time.sleep(.5)
chan.send("y")
elif d == "quit_ssh\n":
remote_conn.close()
sys.exit()
else:
chan.send(d)
except EOFError:
# user hit ^Z or F6
remote_conn.close()
pass
except KeyboardInterrupt:
remote_conn.close()
sys.exit()
def get_serv():
global serv
serv = input("COM: ")
try:
serv = int(serv)
except:
get_serv()
def get_portx():
global portx
portx = input("Port: ")
try:
portx = int(portx)
except:
get_portx()
print("\n(╯°□°)╯_- \u001b[31m♥\033[39m FortiSSH Client \u001b[31m♥\033[39m\n")
serv = 0
portx = 0
serv_list = [17, 18, 19, 200]
while serv not in serv_list:
get_serv()
while not 0 < portx < 49:
get_portx()
if serv == 17:
ip = '192.168.40.17'
username = 'XXXXXXXX'
password = 'XXXXXXXX'
port = "30" + f"{portx:02}"
elif serv == 18:
ip = '192.168.40.18'
username = input("User name: ")
password = input("Password: ")
port = "30" + f"{portx:02}"
elif serv == 19:
ip = '192.168.40.19'
username = 'XXXXXXXX'
password = 'XXXXXXXX'
port = "22" + f"{portx:02}"
elif serv == 200:
ip = '192.168.41.200'
username = 'XXXXXXXX'
password = 'XXXXXXXX'
port = "30" + f"{portx:02}"
# username = input("User name: ")
# password = pwinput.pwinput(prompt="Password: ", mask="•")
# port = 3001
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
# initiate SSH connection
remote_conn_pre.connect(ip, username=username, password=password, port=port, look_for_keys=False, allow_agent=False)
print(f"\nSSH connection established to {ip}, Port {portx}")
# Use invoke_shell to establish an 'interactive session'
remote_conn = remote_conn_pre.invoke_shell()
shell(remote_conn)
remote_conn.close()
I've tried a few different things, but can't seem to come up with a solution. Please help!
Hello I need help with my code. It keeps giving me authentication-errors.
Can you check it out for me?
All I needed was the code to authenticate successfully and save the working login in a txt-file and the bad login (wrong password) in another txt-file. It works with smtp but keeps giving me an error on imap.
See the code below.
Thanks
The logins in accounts.txt are in the following format email:password
...
import imaplib
import ssl
import socket
import getpass
import re
import socks
import codecs
import unicodedata
import random
from multiprocessing.pool import ThreadPool
# PROXY_TYPE_HTTP
# PROXY_TYPE_SOCKS5
proxy_type = socks.PROXY_TYPE_HTTP
use_proxies = False
thead_count = 1
use_encrpytion = False
accounts = []
accounts_checked = 0
accounts_valid = []
accounts_invalid = []
proxies = []
def check_account(email, password):
try:
if (use_proxies):
proxy = random.choice(proxies)
proxy_host = proxy.split(':')[0]
proxy_port = int(proxy.split(':')[1])
socks.setdefaultproxy(proxy_type, proxy_host, proxy_port)
socks.wrapmodule(imaplib)
mailserver = imaplib.IMAP4_SSL(('mail.' + re.search('#((\w|\w[\w\-]*?\w)\.\w+)', email).group(1)), 993)
mailserver.login(str(email), str(password))
mailserver.close()
return True
except imaplib.IMAP4.error:
print ("Log in failed.")
return False
def get_status(account):
global accounts_checked, accounts
if (':' not in account):
return False
email = account.split(':')[0]
password = account.split(':')[1]
valid = check_account(email, password)
if (valid):
print("Valid: ", account)
f1 = open("connect.txt", "a+")
f1.write(account)
f1.close()
accounts_valid.append(account)
else:
f2 = open("not_connect.txt", "a+")
f2.write(account)
f2.close()
accounts_invalid.append(account)
accounts_checked += 1
print("(" + str(accounts_checked) + "/" + str(len(accounts)) + ")")
return valid
if __name__ == "__main__":
if (use_proxies):
print("Reading \"proxies.txt\"...")
with open("proxies.txt") as f:
for line in f:
if (':' in line):
proxies.append(line)
print("Found " + str(len(proxies)) + " proxies.")
print("Reading \"accounts.txt\"...")
with codecs.open("accounts.txt", encoding='utf-8') as f:
for line in f:
line = unicodedata.normalize('NFKD', line).encode('ascii','ignore').decode('ascii')
if (':' in line):
accounts.append(line.replace("\n", "").replace("\t", ""))
print("Found " + str(len(accounts)) + " accounts.")
print("Creating thread pool...")
pool = ThreadPool(thead_count)
results = pool.map(get_status, accounts)
pool.close()
pool.join()
print("Done checking, writing output...")
print("Completed!")
...
you should create a minimal example, in my case I cannot log in using
imaplib but I do not wrap with the socket stuff.. Why is the ssl
sockets not automatic?
def get_mail_client(email_address):
print(password)
mail = imaplib.IMAP4_SSL(SMTP_SERVER, SMTP_PORT)
mail.login(email_address, password)
return mail
def start(name):
# Use a breakpoint in the code line below to debug your script.
mailClient = get_mail_client(EMAIL)
status, messages = mailClient.select('INBOX')
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
print(messages)
print(messages[0])
Unable to produce from the device, made a separate function in running a simple method wherein I have a list of devices and command.
But from this script, seems like I can't send the command to the device? I'm not sure whether script can connect successfully. So I put a print on connect to device part just to determine the location.
From the output of the print is
Connected 0 <-from beg_rm
THIS IS THE COMMAND show ip int brief <-send_cmd
Would like to ask if my method is correct in connect and sending command using this function and argument?
#!/usr/bin/python2
#Required Modules
import sys
sys.path.append("/home/lab/Desktop/pexpect-2.3")
import sys, pexpect, re, getpass, threading, subprocess, os, time
#from queue import Queue
os.system("clear")
### TEST THE IP ADDRESS IF REACHABLE
def ping_ip(ip):
#global gips
rstlongstr = ''
(output,error) = subprocess.Popen((['ping', ip, '-c', '2']), stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate()
if b'bytes from' in output:
#rstlongstr = rstlongstr + ip
#print rstlongstr
return "Reachable" + ip
elif b'Host Unreachable' in output:
return "Down"
else:
return "UNKNOWN"
### SEND COMMAND TO DEVICE
def send_cmd(child,com):
print "THIS IS THE COMMAND", com
child.sendline(com)
child.expect("#")
print(child.before)
return result
### CONNECT TO DEVICE
def beg_rm(ip,uname,ppass,enpass):
print "Begin remote connection",ip
print "\nCRED",uname,ppass,enpass
child = pexpect.spawn('ssh %s#%s' % (uname, ip))
i = child.expect(['[P|p]assword: ','[U|u]sername: ','continue connecting (yes/no)?','#'],timeout=5)
if i == 0:
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 0"
return i
elif i == 1:
child.sendline(uname)
child.expect('Password: ')
child.sendline(ppass)
child.expect('>')
child.sendline(enpass)
print "Connected 1"
return i
elif i == 2:
child.sendline('yes')
i = child.expect([pexpect.TIMEOUT, '[P|p]assword: '])
if i == 0:
print "Error connecting ",ip
return
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 2"
return i
elif i == 3:
pass
def main():
print('-'*50)
while True:
print('------------------------- ue Network Tools -------------------------------')
print('--- *********************************************************************** ---')
print('-'*80)
print'[1] Troubleshoot'
print'[2] Custom Tshoot'
print'[3] Wireless LAN'
print'[4] Confinder'
print'[q] exit\n'
#Select Function
input_select = raw_input('Please select a function: ')
input_select = str(input_select)
if input_select == 'q' or input_select == 'Q':
sys.exit()
elif input_select == '1':
#Read the txt file
devtxt = open('devices.txt')
devlist = devtxt.read().splitlines()
print devlist
cmdtxt = open('command.txt')
cmdlist = cmdtxt.read().splitlines()
print cmdlist
#tuname = raw_input("TACACS Username: ")
#tpass=getpass.getpass("TACACS Password: ")
#epass=getpass.getpass("Enable Password: ")
tuname = "test"
tpass = "test"
epass = "enter"
#LIST
gips = []
threadslist = []
#Verify Reachability
for ips in devlist:
print "Processing the list to function", ips
response = ping_ip(ips)
result = ('%s \n' % (response))
print result
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response)):
forgips = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response))
strgips = ''.join(forgips)
#print "FORGIPS 2",strgips
gips.append(strgips)
pass
else:
pass
print "\nList of reachable devices to be sent for threading:\n", gips
## LOOP REACHABLE DEVICE AND COMMAND
for x in gips:
child = beg_rm(x,tuname,tpass,epass)
for y in cmdlist:
send_cmd(child,y)
if __name__ == '__main__':
main()
Trace back
Traceback (most recent call last):
File "2jb.py", line 142, in <module>
main()
File "2jb.py", line 139, in main
send_cmd(child,y)
File "2jb.py", line 31, in send_cmd
child.sendline(com)
AttributeError: 'int' object has no attribute 'sendline'
child = beg_rm(x,tuname,tpass,epass)
for y in cmdlist:
send_cmd(child,y)
def send_cmd(child,com):
print "THIS IS THE COMMAND", com
child.sendline(com)
...
beg_rm() returns an integer, which is then passed as the child argument to send_cmd().
It seems like you're expecting beg_rm() to return the child object, instead of an integer?
I have a server:
import threading
import paramiko
import subprocess
import sys
import socket
host_key = paramiko.RSAKey(filename='test_rsa.key')
class Server(paramiko.ServerInterface):
def _init_(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_password(self, username, password):
if(username=='justin') and (password == 'lovesthepython'):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((server, ssh_port))
sock.listen(100)
print '[+] Listening for connection ...'
client, addr = sock.accept()
except Exception, e:
print '[-] Listen failed: ' + str(e)
sys.exit(1)
print '[+] Got a connection!'
try:
bhSession = paramiko.Transport(client)
bhSession.add_server_key(host_key)
server = Server()
try:
bhSession.start_server(server=server)
except paramiko.SSHException, x:
print '[-] SSH Negotiation Failed'
chan = bhSession.accept(20)
print '[+] Authenticated!'
print chan.recv(1024)
chan.send('Welcome to bh_ssh')
while True:
try:
command= raw_input("Enter command: ").strip('\n')
if command != 'exit':
chan.send(command)
print chan.recv(1024) + '\n'
else:
chan.send('exit')
print 'exiting'
bhSession.close()
raise Exception ('exit')
except KeyboardInterrupt:
bhSession.close()
except Exception, e:
print '[-] Caught exception: ' + str(e)
try:
bhSession.close()
except:
pass
sys.exit(1)
My code to connect to this is:
import threading
import paramiko
import subprocess
def ssh_command(ip, port, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port, username=user, password=passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.send(command)
print ssh_session.recv(1024)
while True:
command = ssh_session.recv(1024)
try:
cmd_output = subprocess.check_output(command, shell=True)
ssh_session.send(cmd_output)
except Exception,e:
ssh_session.send(str(e))
client.close()
return
ssh_command('IP_ADDRESS_HERE',PORT_HERE,'justin','lovesthepython','id')
When I try to use these on separate PCs and use public IP addresses it won't connect. The server I bind to 0.0.0.0 and then use the public IP address of the server's computer to the client code. I imagine I am doing something fairly obvious wrong. If anyone can help, it would be very much appreciated.
I'm new in cherrypy, and I try to develop a small application by using this framework. My problem is, this application can serves well and browser can access when cherrypy works in undaemonizer mode. But when I write code by using cherrypy.process.plugins.Daemonizer(), cherrypy started in background, and it listen on specific port, but browser will get a connection refused( iptables or ufw already shutted down but still inaccessible ). The incredible thing is, when I start it with daemoned mode, I can still start a undaemoned process , and they listen on the same port. I wonder why would this happend, and how to solve it?
Simply saids: With Daemonizer starts, cherrypy listened on specified port, but browser connection refused; without Daemonizer, cherrypy works very well.
Thanks alot
with my code
from optparse import OptionParser
from cherrypy.process.plugins import Daemonizer
from cherrypy.process.plugins import PIDFile
import cherrypy
import json
import urllib
import datetime
try:
import cPickle as pickle
except:
import pickle
import time
import base64
import os
import sys
'''
cherrypy class
'''
class Index(object):
#cherrypy.expose
def index(self):
return "Say hello to the yellow elephant"
class System(object):
#cherrypy.expose
def env(self, token):
local_token = Token()
if local_token.AuthToken(token) is True:
env = get_env()
return json.dumps(env)
return '{"errcode", "Invalid token"}'
class Jmx(object):
#cherrypy.expose
def get(self, token, host, port, qry):
local_token = Token()
if local_token.AuthToken(token) is True:
url = 'http://' + host + ':' + port + '/jmx?qry=' + qry
jmx = urllib.urlopen(url)
jmx_data = jmx.read().replace('\n', '')
jmx.close()
return jmx_data
return '{"errcode", "Invalid token"}'
"""
command uses base64 encode by using http post method
"""
class Command(object):
def __init__(self):
self.fname = datetime.datetime.now().strftime('%Y-%m-%d_%M-%M-%S') + '.log'
#cherrypy.expose
def run(self, token, command):
local_token = Token()
command = base64.b64decode(command)
if local_token.AuthToken(token) is True:
os.popen(command + ' 2>&1 > /usr/lib/agent/output/' + self.fname)
return '{"errcode", "Invalid token"}'
#cherrypy.expose
def readlog(self, token):
local_token = Token()
if local_token.AuthToken(token) is True:
log = open('/usr/lib/agent/output/' + self.fname)
lines = log.readlines()
log.close()
return json.dumps(lines, ensure_ascii=False)
return '{"errcode", "Invalid token"}'
"""
First time access from central, it will create a new token on slave node, the token is pickle.dump(cacl_mysql_passwd(conf['agent']['secret']))
By token created , if central makes change to secret, the slave node will be inaccessible!!!
"""
class Token(object):
def AuthToken(self, token):
if(os.path.isfile('/usr/lib/agent/key/authenticate.key')) is False:
return self.CreateToken(token)
else:
try:
k = open('/usr/lib/agent/key/authenticate.key', 'rb')
tokenizer = pickle.load(k)
k.close()
if token == tokenizer:
return True
else:
return False
except IOError, e:
return '{"errcode":"' + str(e).replace('\n', '<br/>') + '"}'
#cherrypy.expose
def CreateToken(self, token):
if(os.path.isfile('/usr/lib/agent/key/authenticate.key')) is False:
try:
k = open('/usr/lib/agent/key/authenticate.key', 'wb')
pickle.dump(token, k)
k.close()
return True
except IOError, e:
return '{"Exception":"' + str(e).replace('\n', '<br/>') + '"}'
else:
return '{"errcode":"token exists"}'
class Controller:
def __init__(self, pidfile='/var/run/agent/agent.pid', host='0.0.0.0', port=30050):
self.port = port
self.host = host
self.pidfile = pidfile
self.settings = {
'global': {
'server.socket_port': port,
'server.socket_host': host,
'server.socket_file': '',
'server.socket_queue_size': 5,
'server.protocol_version': 'HTTP/1.1',
'server.log_to_screen': True,
'server.log_file': '',
'server.reverse_dns': False,
'server.thread_pool': 10,
'server.environment': 'production',
'engine.timeout_monitor.on': False
}
}
def start(self):
if os.path.exists(self.pidfile):
sys.stderr.write('PID file exists, server running?\n')
sys.exit(1)
else:
Daemonizer(cherrypy.engine, stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr').subscribe()
PIDFile(cherrypy.engine, self.pidfile).subscribe()
cherrypy.tree.mount(Index(), '/')
cherrypy.tree.mount(System(), '/system')
cherrypy.tree.mount(Command(), '/command')
cherrypy.tree.mount(Jmx(), '/jmx')
cherrypy.config.update(self.settings)
cherrypy.engine.start()
cherrypy.engine.block()
def stop(self):
cherrypy.config.update(self.settings)
if os.path.exists(self.pidfile):
cherrypy.engine.stop()
cherrypy.engine.exit()
try:
process = open(self.pidfile).read().strip()
if process != 0:
os.popen('kill -9 %s' % process)
os.remove(self.pidfile)
except IOError, e:
sys.stderr.write(str(e))
else:
sys.stderr.write('PID file does not exist, server gone?\n')
sys.exit(1)
if '__main__' == __name__:
cherrypy.engine.autoreload.stop()
cherrypy.engine.autoreload.unsubscribe()
syntax = 'Syntax: %prog -b 192.168.1.1 -s start'
parser = OptionParser(usage=syntax)
ip = os.popen('hostname -i').read().strip()
hostname = os.popen('hostname --fqdn').read().strip()
parser.add_option('-b', '--bind', action='store', type='string', dest='bind', default=ip, help='Inner network IP address, default value is hostname -i')
parser.add_option('-s', '--signal', action='store', type='string', dest='signal', help='Valid signal is {start|stop|restart}')
options, args = parser.parse_args()
if len(sys.argv) == 1:
print 'Use %s -h or --help for help.' % sys.argv[0]
else:
if options.signal == '':
print 'Must give -s option\'s value'
else:
daemon = Controller(pidfile='/var/run/agent/agent.pid', host=options.bind)
if 'start' == options.signal:
daemon.start()
elif 'stop' == options.signal:
daemon.stop()
else:
print 'Invalid signal'
sys.exit(1)