run the python program as service without installing python? - python

I have written a program that can change the system's IP address/password automatically at a specific time. In addition, it has two separate python files.
The first one is a program that runs the main program under the service, retrieves the desired information from the user and stores it in a `.txt' file.
# Import/Lib
import os
import sys
import pysc
import time
# Services
if __name__ == '__main__':
service_name = 'test4'
script_path = os.path.join(
os.path.dirname(__file__)+"\\"+"Run.exe"
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
print("CreateService SUCCESS")
pysc.start(service_name)
print("StartService SUCCESS")
# Input data
time_today = input("Enter a Time (MM:SS): ")
date_today = input("Enter a Date (YYYY-MM-DD): ")
adapter_name = input("Enter your interface name: ")
interface_name = "\"" + adapter_name + "\""
static_ip = input("Enter your static ip: ")
subnet = input("Enter your subnet mask: ")
gateway = input("Enter your gateway: ")
time.sleep(0.5)
print("")
pass_complexity = "Windows password complexity rules:""\n" \
"-Password must not contain the user's account name or more than two consecutive "\
"characters from the user's full name.""\n"\
"-Password must be six or more characters long.""\n"\
"-Password must contain characters from three of the following four categories:""\n"\
" .Uppercase characters A-Z (Latin alphabet)""\n"\
" .Lowercase characters a-z (Latin alphabet)""\n"\
" .Digits 0-9""\n"\
" .Special characters (!, $, #, %, etc.)""\n"
print(pass_complexity)
password = input("New password: ")
conform_pass = input("Confirm password: ")
stop = True
while stop == True:
if password == conform_pass:
print("Input info completed")
print("Interface adapter", interface_name + ":")
print("IPv4 Address. . . . . . . . . . . : ", static_ip)
print("Subnet Mask . . . . . . . . . . . : ", subnet)
print("Default Gateway . . . . . . . . . : ", gateway, "\n")
print("Your password:", password, "\n")
stop = False
else:
print("Sorry, passwords do not match.", "\n")
password = input("New password: ")
conform_pass = input("Confirm password: ")
# Write file
file_name = os.path.dirname(__file__)+"\\"+"Network Monitoring Utility.txt"
my_file = open(file_name, 'w')
my_file.write(time_today+" ")
my_file.write(date_today+" ")
my_file.write(interface_name+" ")
my_file.write(static_ip+" ")
my_file.write(subnet+" ")
my_file.write(gateway+" ")
my_file.write(password+" ")
my_file.close()
wait = input("Please enter for exit.")
The second program compares the system clock with the read time by reading the desired .txt file information. If the system date and time are the same as the date and time entered, it will change the system's IP address/password.
# Import Lib
import subprocess
import getpass
from datetime import date
import datetime
import time
time.sleep(90)
# Read data
my_file = open('Network Monitoring Utility.txt', 'r')
data = my_file.read()
data = data.split()
my_file.close()
time = data[0]
set_date = data[1]
interface_name = data[2]
static_ip = data[3]
subnet = data[4]
gateway = data[5]
password = data[6]
# Check data and time and change ip, subnet mask, gateway and password
stop = True
while stop == True:
now_time = str(datetime.datetime.now().time())
now_date = str(date.today())
if now_date == set_date and now_time > time:
stop = False
subprocess.check_call("netsh interface ipv4 set address name="
+ interface_name + " " + "static" + " " + static_ip + " " + subnet + " "
+ gateway, shell=True)
username = getpass.getuser()
subprocess.check_call("net users " + username + " " + password, shell=True)
When I run this program in Pycharm it runs without any problems. But when I convert both programs with pyinstaller to '.exe', the program will not run under service. this will cause an error.
filenotfounderror: [winerror 2] the system cannot find the file specified.
This message is also because the program requires a Python executable file to run severely on the service.
How to run this service without having to install Python on a system?

Related

Python telnet not showing result

with python script I want to make some configuration on mikrotik routers, looks like script is right and no gives errors but ends without printing command outputs
import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"
tn = telnetlib.Telnet(dev_ip, timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")
running on Ubuntu Desktop
problem solved after putting:
time.sleep(1)
before Showcmdoutput = tn.read_very_eager().decode('ascii')
tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')

Executable will run on any computer, but will only preform properly my computers with python

I'm an intern and I'm trying to make a simple lookup script for my company that will take a SQL database and search through it to make a more user readable list. I got the script to do roughly what I want and am now trying to make an executable that people in my office can try out. The problem is that the script seems to only preform as intended on machines with python. The script will open on the PC every PC, but when I feed it the SQL file it does not populate the text field.
I tried using pyinstaller, py2exe, and python build -> (python file.py build) with no luck. I followed Reedinationers compile guide here. My python exe will not run 2 other python exe's
import re
import tkinter as tk
from tkinter.filedialog import askopenfilename
from _sqlite3 import Error
from tkinter import PhotoImage
# Link the .DB file
###########################################
def create_connection(db_file):
try:
conn = _sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
###########################################
try:
UserFile = open("UserFriend.txt", "w")
#Check for File if one does not exist make it
except:
UserFile = open("UserFriend.txt", "w+")
###########################################
global Error
Error = False
###########################################
def Friendly_Output(line, number, times, Error_Finder, Time_Stamp, Search_Count):
#Error_List = []
#setup = []
#print(Search_Count)
############################################################################
if "viewDidLoad() - Got a valid" in line and Error == False:
setup.append("\nFound mac address here \t\t\t\t\t| "+ Time_Stamp)
else:
pass
########################################################
if Error == False and "wifiScanTimerEvent(timer:)" in line:
#UserFile.write("\nPinged nearby wifi with NIC " + str(times) + " time(s)")
if times >= 10:
spacing = " \t| "
else:
spacing = "\t\t\t| "
setup.append("\nPinged nearby wifi with NIC " + str(times) + " time(s)" + spacing + Time_Stamp)
########################################################
if Error == False and "rssi:" in line:
strength = line[15:18]
if int(strength) >= -30:
Sname = "Excellent"
space = "\t\t\t\t\t| "
if int(strength) <= -30 and int(strength) >=-64:
Sname = "Very Good"
space = "\t\t\t\t\t| "
elif int(strength) <= -64 and int(strength) >=-70:
Sname = "Okay"
space = "\t\t\t\t\t| "
elif int(strength) <= -70 and int(strength) >=-80:
Sname = "Bad"
space = "\t\t\t\t\t| "
elif int(strength) <= -80 and int(strength) >=-90:
Sname = "Useless"
space = "\t\t\t\t\t| "
else:
pass
setup.append("\nThe signal strength is " + Sname + space + Time_Stamp)
else:
pass
if Error == False and "refrigeratorTapped()" in line:
#UserFile.write("\nTransfer to Pin Entry")
setup.append("\nTransfer to Pin Entry Screen \t\t\t\t\t| " + Time_Stamp)
else:
pass
########################################################
if Error == False and "applianceTapped() - segue_to_wifi_select_sid" in line:
#UserFile.write("\nTransfer to wifi selection page")
setup.append("\nTransfer to wifi selection page \t\t\t\t\t| " + Time_Stamp)
else:
pass
########################################################
if Error == False and "prepare(for:sender:) - segue_to_prod_wifi_setup_sid" in line:
#UserFile.write("\nTransfer to Wifi crediental entry screen")
setup.append("\nTransfer to Wifi crediental screen \t\t\t\t | " + Time_Stamp)
else:
pass
if Error == False and "addWifiNameToParamOut(wifi:)" in line:
#UserFile.write("\nAdded wifi to data send list")0
setup.append("\nAdded wifi to data send list \t\t\t\t\t| " + Time_Stamp)
else:
pass
########################################################
if Error == False and "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with" in line:
#UserFile.write("\nSent MacAddress, apiKey, and devicePin to Cloud")
setup.append("\nSent device information to Cloud \t\t\t\t\t| " + Time_Stamp)
else:
pass
########################################################
if Error == False and r"setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice" in line:
#UserFile.write("\nSuccessful sending of MacAddress, apiKey, and devicePin to Cloud")
setup.append("\nSuccessful sending of MacAddress, apiKey, and devicePin to Cloud # " + Time_Stamp)
else:
pass
########################################################
if Error == False and "onRecordButton" in line:
#UserFile.write("\nEntry applied to appliance list (Continue Button)")
setup.append("\nEntry applied to appliance list\t\t\t\t\t| " + Time_Stamp)
else:
pass
########################################################
if Error == False and "updateApplianceRecord() - upda" in line:
#UserFile.write("\nUser notified of success")
#UserFile.write("\nEnd of Setup number: " + str(number) + "\n\n")
setup.append("\n\t\t\t\t\t|\nEnd of Setup number: " + str(number)+ "\t\t\t\t\t| " + "\nUser notified of success \t\t\t\t\t| " + Time_Stamp)
#Error_List.append("\n\nEnd of Setup number: " + str(number)+ "\nUser notified of success # " + Time_Stamp)
else:
pass
#ERROR GRABS
#######################################################################################
if "0110" in line:
#UserFile.write("\nERROR: No Bluetooth device was found")
setup.append("\nERROR: No Bluetooth device was found \t\t\t| " + Time_Stamp)
Error_List.append("\nERROR: No Bluetooth device was found \t\t\t| " + Time_Stamp)
elif "ErrorCode: loginCloudNew" in line:
setup.append("\nIncorrect Username or password attempt\t | " + Time_Stamp)
Error_List.append("\nIncorrect Username or password attempt\t | " + Time_Stamp)
elif "0120" in line:
#UserFile.write("\nERROR: No Wifi or Poor Connection")
setup.append("\nNo Wifi or Poor Connection \t\t\t\t\t| " + Time_Stamp)
Error_List.append("\nNo Wifi or Poor Connection \t\t\t\t\t| " + Time_Stamp)
elif "0130" in line:
#UserFile.write("\nERROR: User searched for appliance but none was found")
setup.append("\nSearched for appliance nothing was found| "+ Time_Stamp)
Error_List.append("\nSearched for appliance nothing found\t\t\t\t| " + Time_Stamp)
elif "300" in line:
#UserFile.write("\nERROR: Wifi List is empty. Restarting configure process.")
setup.append("\nWifi List is empty. \t\t\t\t\t| " + Time_Stamp)
Error_List.append("\nWifi List is empty. \t\t\t\t\t| " + Time_Stamp)
elif "310" in line:
#UserFile.write("\nERROR: Lost BluetoothConnection in Wifi Picker Screen. Restarting configure process.")
setup.append("\nBluetooth Connection lost on WiFi screen| " + Time_Stamp)
Error_List.append("\nBluetooth Connection lost on WiFi screen| " + Time_Stamp)
elif "1010" in line:
#UserFile.write("\nERROR: User opted to skip wifi Setup")
setup.append("\nUser opted to skip wifi Setup at\t\t\t\t\t| " + Time_Stamp)
Error_List.append("\nERROR: User opted to skip wifi Setup\t\t\t\t| " + Time_Stamp)
elif "1011" in line:
#UserFile.write("\nERROR: There was an empty text field when trying to configure wifi")
setup.append("\nUser left text field empty \t\t\t\t\t| " + Time_Stamp)
Error_List.append("\nUser left text field empty \t\t\t\t\t| " + Time_Stamp)
elif "1012" in line:
#UserFile.write("\nERROR: Bluetooth Disconnected, Reason Unknown")
setup.append("\nBluetooth Disconnected, Reason Unknown \t| " + Time_Stamp)
Error_List.append("\nBluetooth Disconnected, Reason Unknown \t| " + Time_Stamp)
elif "1013" in line:
#UserFile.write("\nERROR: The provision watchdog timer has timed out without response from NIC")
setup.append("\nUser experienced connection timeout \t\t\t\t| " + Time_Stamp)
Error_List.append("\nUser experienced connection timeout \t\t\t\t| " + Time_Stamp)
elif "1029" in line:
#UserFile.write("\nERROR: The Cloud Service reports error. Error in log")
setup.append("\nThe Cloud Service reports error.\t\t\t\t\t| " + Time_Stamp)
Error_List.append("\nThe Cloud Service reports error.\t\t\t\t\t| " + Time_Stamp)
elif "1030" in line:
#UserFile.write("\nERROR: The provisioning has failed. The device and apikey key were not returned")
setup.append("\nDevice and apikey key were not returned | " + Time_Stamp)
Error_List.append("\nDevice and apikey key were not returned | " + Time_Stamp)
if Search_Count == Loop_Count-2:
Search_Func(Error_List,setup,Error_Finder,Search_Count)
#Need to clear the Error_List when the Error Locator button is press when it is press it is running search again and adding the the errors back as a 2nd duplicate
################################################################################################
def Search_Func(Error_List, setup, Error_Finder,Search_Count):
if Error_Finder == True:
if not Error_List:
Text_Box.insert('1.0',"There are no Errors Found")
for text in reversed(Error_List):
Text_Box.insert('1.0', text)
UserFile.write(text)
else:
for text in setup:
Text_Box.insert('1.0', text)
UserFile.write(text)
#Main Function (cursor setup, variables for count ping and hits)
################################################################################
def main(filename,Error_Finder):
list = create_connection(filename) # create_connection(database)
global Loop_Count
cur = list.cursor()
cur.execute("SELECT * from error_log ")
rows = cur.fetchall()
count = 0
Search_Count = 0
pings = 1
hits = 0
info = []
Loop_Count = rows[:]
Loop_Count = len(Loop_Count)
for row in rows:
info.append(row[2])
#Regex Grab
#########################################################################
m = re.search(r"(?s)id: (?P<username>.+?) - (?P<password>.+?)'.*Appliance: (?P<modelnumber>\S+).*macAddress: (?P<macaddress>.+?)'.*appl name: (?P<applname>\S+)", str(info))
if (info): # - (?P<password>.+?)'.*App...
try:
if Error_Finder == False:
UserFile.write( 'Username: {}, Modelnumber: {}, Macaddress: {}, applname: {}\n\n'.format(m.group('username'),m.group('modelnumber'),m.group('macaddress'),m.group('applname')))
Text_Box.insert('1.0','\n\nUsername:\t\t {}\nModelnumber:\t\t {}\nMacaddress:\t\t {}\napplname:\t\t {}\n\n'.format(m.group('username'),m.group('modelnumber'),m.group('macaddress'),m.group('applname')))
#Search counters and Callers Password: {},
#########################################################################
count = 0 # reset count
pings = 1 # reset pings
hits = 0 # reset hits
for row in rows:
Search_Count += 1
Friendly_Output(str(row[2]), count, pings, Error_Finder,str(row[1]),Search_Count)
info.append(row)
if "onRecordButton - Calling" in str(row):
count += 1
pings = 1
if "wifiScanTimerEvent(timer:)" in str(row):
pings = pings + 1
except:
print("Type None Occured")
# GUI
################################################################################
window = tk.Tk()
window.title("Viking Range SuChef Diagnostics")
width_value = window.winfo_screenwidth()
height_value = window.winfo_screenheight()
window.geometry(f"{width_value}x{height_value}+0+0")
text_height = 50#height_value/20
text_width = 115#width_value/9.05
photo = PhotoImage(file = "glass-teal.png")
background_image=tk.PhotoImage(file = "glass-teal.png")
background_image = background_image.zoom(2)
background_label = tk.Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
def Load_File():
global fname
global Error_Finder
global Error_List
global setup
Error_List = []
setup = []
fname = askopenfilename(filetypes = (("SQL Database", "*.db"), ("All Files","*.*")))
Text_Box.delete(1.0,tk.END)
Error_Finder = False
main(fname, Error_Finder)
return fname
def Clear_Log():
Text_Box.delete(1.0,tk.END)
def Find_Errors():
try:
if fname:
Text_Box.delete(1.0,tk.END)
Error_Finder = True
Search_Func(Error_List, None, Error_Finder,None)
except:
Text_Box.insert('1.0', "You must First select a File")
def ViewFunc():
try:
if fname:
ErrorFinder = False
Text_Box.delete(1.0,tk.END)
Search_Func(None, setup, Error_Finder, None)
except:
Text_Box.insert('1.0', "You must first select a File")
#Label
label = tk.Label(text = "Viking Range Service Application", font = "Arial") #fg = "blue"
label.pack()#grid(column = 0, row = 0)
#Browse_Button
Browse_Button = tk.Button(text = "Browse Files",cursor="cross", command = Load_File)
Browse_Button.pack()#grid(column = 0, row = 1)
Clear_Button = tk.Button(text = "Clear", command = Clear_Log)
Clear_Button.pack()#grid(column = 0, row = 1)
#Text field
Text_Box = tk.Text(height = int(text_height), width = int(text_width), background = "black", foreground = "white")
#Text_Box.place(anchor = tk.CENTER)
Error_Button = tk.Button(text = "Error Locator", command = Find_Errors)
Full_DocB = tk.Button(text = "View Full Document", command = ViewFunc)
Error_Button.pack()#grid(column = 0, row = 1)
Full_DocB.pack()
Text_Box.pack()#grid(column = 0, row = 2)
window.mainloop()
############################################################################################
The expected process to launch the .exe browse for SQL file select it and receive a readable output in the black text box and a file is saved with nearly the same text. What is happening is that a User can launch and select a file but the text box is never populated and the file is created, but it is empty.

script with telnet write is not functioning

I have this program that access devices and change its hostname based from csv file but after entering the user/password script doesn't write any or seem like its tn.write is not running.
While logs from device shows that the python script can access the device. Also no error when running this script.
import csv
import telnetlib
import getpass
import sys
import time
##from prettytable import PrettyTable
def main():
#open csv file, then put to variable csvfile.
with open(input("Input the CSV filename: ")) as csvfile:
riphostCSV = csv.reader(csvfile, delimiter=',')
#Put the data as list from excel.
ipaddress = []
nhostname = []
## Menu = PrettyTable()
## Menu.field_names=['IPadd','Nhostname']
#Action - Put the data from excel to variable[list]
for col in riphostCSV:
ipadr = col[0]
nhost = col[1]
ipaddress.append(ipadr)
nhostname.append(nhost)
#List of devices from CSV file
print("LIST OF DEVICES")
for i in ipaddress:
print(i, nhostname[ipaddress.index(i)])
dev = ipaddress
print ("Host: ",dev)
user = input("Enter your username: ")
password=getpass.getpass("Enter Your Password Here: ")
## password = getpass.getpass()
print ("Now accessing the devices " + i)
dev = i.strip()
tn = telnetlib.Telnet(dev)
print("host:",dev)
tn.read_until(b"Username:")
tn.write(user.encode("ascii") + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode("ascii") + b"\n")
tn.read_until(b"#")
tn.write(b"conf t \n")
time.sleep(1)
tn.write(b"hostname test33 \n")
tn.write(b"exit \n")
tn.write(b"wr mem \n")
## tn.close()
## break
main()
OUTPUT
nput the CSV filename: iphost.csv
LIST OF DEVICES
192.168.137.50 lab-sw01
Host: ['192.168.137.50']
Enter your username: cisco
Warning (from warnings module):
File "C:\Users\GlobalNOC\AppData\Local\Programs\Python\Python37-32\lib\getpass.py", line 100
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Enter Your Password Here: cisco
Now accessing the devices 192.168.137.50
host: 192.168.137.50
Thanks

Python 2.7 telnetlib For Loop

I am writing a simple script in python , to telnet multiple cisco switches and add vlans. I am testing my script in UNET LABS or latest EVE-NG.
When I telnet to multiple switches using FOR loop and call
tn = telnetlib.Telnet(HOST)
from with in loop , it only telnets to last value in variable HOST i.e. 10.1.1.7
Here is my code,
#!/usr/bin/env python
import getpass
import sys
import telnetlib
user = raw_input("Enter your telnet username: ")
password = getpass.getpass()
for h in range (2,8):
print "Telnet to host" + str(h)
HOST = "10.1.1." + str(h)
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("conf t\n")
for n in range (10,20):
tn.write("vlan " + str(n) + "\n")
Following code is working for me. Put all of your IPs in a sheet (IP_test.txt).
import getpass
import sys
import telnetlib
user = "YOURUSER"
password = "YOURPASSWORD"
with open('IP_test.txt') as file:
for HOST in file:
        tn = telnetlib.Telnet(HOST)
        tn.read_until("login: ")
        tn.write(user + "\n")
        if password:
            tn.read_until("Password: ")
            tn.write(password + "\n")
            tn.write("Command1\n")
            tn.write("Command2\n")
            print(tn.read_all())
This python script below works for me for the same purpose
#!/usr/bin/env python3
import getpass
import telnetlib
user = input("Enter your Telnet Username: ")
password = getpass.getpass()
DeviceList=open('/home/tt/Hostname.txt')
for HOST in DeviceList:
print('Configuring on Device : ',HOST)
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"enable\n")
EnPass=input('Enter your Enable password : ')
tn.write(EnPass.encode('ascii')+b'\n')
c=open('/home/tt/Commands.txt')
for i in c:
tn.write(i.encode('ascii')+b'\n')
c.close()
print(tn.read_all().decode('ascii'))
tn.close()
DeviceList.close()}

Python print adds new line and 0

Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:
C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
0 <------------MY ISSUE
C:\Python30>plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
<------------WHAT I EXPECT
Here is my code:
def read_dev():
# Print statement here for debugging
print ("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
cur_dev = os.system("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
return(cur_dev)
HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
cur_dev is getting the result code returned by the plink command, which is 0. Your read_dev function returns this code, so print(read_dev()) prints the 0.
Just say read_dev() instead of print(read_dev()).
It doesn't "print zero". It prints cur_dev which is returned by read_dev function, which happens to be zero. And it does so, because you told it to. Remove print function and it won't print anything."
If you want to explicitly set the exit code use sys.exit(cur_dev). Simply using a return value from a function does not do what you want it to.

Categories