I have a python script which contains the following function:
def upload2server(file):
host_name = 'example.ex.am.com'
port_num = '432'
user_name = 'user'
password = 'passw'
web_path = '/example/files/'
full_webpath = user_name + '#' + host_name + ':' + web_path + args.key
pre_command = 'sshpass -p "' + password + '" scp -P' + ' ' + port_num + ' '
scp_comm = pre_command + file + ' ' + full_webpath
os.system(scp_comm)
I'd have 2 questions:
How unsecure is that if I run this script from a remote network using port-forwarding?
Which ways could I make this uploading more secure?
Thanks!
Personally, I would generate an SSH keypair for each host and then you can totally forget about using the password in your scp command. Having your password inline isn't a problem per say but it does mean that your password will get recorded in the ~/.bash_history file of that user.
Related
So I need to have a script that will execute the nsupdate command, to add a record the the ddns database:
#!/usr/local/bin/python3.7
import sys
import os
import time
import subprocess
try:
hostname = sys.argv[1]
IP = sys.argv[2]
except Exception as e:
print('Error: Please enter a number\n')
zone = hostname[-5:]
update = ''
if zone == 'zone1':
print('\nThis will be added to zone1\n')
#add to zone 1
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
os.system('nsupdate -k zone1.key')
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
if zone == 'zone2':
print('This will be added to zone2')
#add to zone 2
os.system('nsupdate -k zone2.key')
#if statement to check IP address is in range
#update = 'update add ' + hostname + ' 86400' + ' A ' + IP
time.sleep(2)
os.system(update)
time.sleep(2)
os.system('send')
time.sleep(2)
os.system('quit')
#time.sleep(3)
print('\nHostname:')
print(hostname)
print('\nIP address: ')
print(IP)
print('\nZone: ')
print (zone)
Above is the code I'm currently working with, please ignore it if its badly written, dont write much python.
I find it executes the first os.system fine, but will not run the next three.
I believe that's because the command line changes from # to > but have got no clue how to still have it execute those commands.
Have tried os.system and subprocess.run/call
even tried call it all in one os.system by going os.system('nsupdate; {update}; send; quit').
Any help would be great.
I have a .sql file which gets an input and runs, I should run it from a python code with some inputs, but it doesn't work. What is problem?
sql file:
declare
--define variables
v_workspace_id NUMBER;
BEGIN
select workspace_id into v_workspace_id
from apex_workspaces
where workspace = upper('&1');
DBMS_OUTPUT.PUT_LINE(v_workspace_id);
apex_application_install.set_workspace_id( v_workspace_id );
apex_application_install.generate_application_id;
apex_application_install.generate_offset;
EXCEPTION
WHEN OTHERS
THEN
RAISE;
END;
part of python file to run this file:
cmd_sql = 'echo quit | sqlplus -S ' + DB_USER + '/' + DB_USER_PWD + '#' + DB_HOST + ' #' + SQL_PATH + '\\' + 'install_apex_apps.sql ' + user_name + ' >> ' + LOG_FILE
os.system(cmd_sql)
user_name is given as an input to sql file.
PL/SQL
Change code to (note the /). Also as #Belayer sugessted in the comment section remove the EXCEPTION section.
SET SERVEROUTPUT ON;
declare
--define variables
v_workspace_id NUMBER;
BEGIN
select workspace_id into v_workspace_id
from apex_workspaces
where workspace = upper('&1');
DBMS_OUTPUT.PUT_LINE(v_workspace_id);
apex_application_install.set_workspace_id( v_workspace_id );
apex_application_install.generate_application_id;
apex_application_install.generate_offset;
END;
/
Python
Linux
import os
DB_USER = 'xxx'
DB_USER_PWD = 'xxx'
DB_HOST = 'xxx'
SQL_PATH = '/home/xxx/Documents/stack/'
LOG_FILE = '/home/xxx/Documents/stack/log.txt'
user_name = 'xxx'
# I override the log file with > for appending use >>
cmd_sql = 'echo quit | sqlplus -S ' + DB_USER + '/' + DB_USER_PWD + '#' + DB_HOST + ' #' + SQL_PATH + 'install_apex_apps.sql ' + user_name + ' > ' + LOG_FILE
os.system(cmd_sql)
with pysftp.Connection(ipaddr, username="uname", password="pass", cnopts=cnopts) as sftp:
sftp.put(uploc + ufile, "/home/pi/PIFTP/dloads/" + ufile)
checkfile = ("/home/pi/PIFTP/dloads/" + ufile)
chfile = pysftp.Connection.isfile(checkfile)
if chfile == True:
print (Style.BRIGHT + "[" + Fore.GREEN + "OK" + Fore.WHITE + "] ")
else:
print (Style.BRIGHT + Fore.RED + ipaddr + " is unacsessible")
As you can see I'm trying to check a file that is just uploaded. In this case "/home/pi/PIFTP/dloads/" + ufile is file's remote download path. What am I missing? Thanks.
Also file arrives before error.
You'll need to use the Connection instance sftp you have, not the class.
chfile = sftp.isfile(checkfile)
I'm new at exporting data, I research all over the net but it was really hard for me to understand, can someone help me to know the basic about it.
This is my main problem: I want to download a specific data from mysql base on the date range I choose in my client, then when I click the download button, I want these data from mysql to be save in my computer together the user have the option to save it as CSV/Excel, I'm using python for my webservice. Thank you
This is my code right know in my webservice:
#api.route('/export_file/', methods=['GET', 'POST'])
def export_file():
if request.method == 'POST':
selectAttendance = """SELECT * FROM attendance"""
db.session.execute(selectAttendance)
db.session.commit()
f = csv.writer(open("file.csv", "w"))
for row in selectAttendance:
f.writerow([str(row)])
return jsonify({'success': True})
In general:
Set the mime header "Content-Type" part of the http header to the corresponding MIME-Type matching your data.
This tells the browser what type of data the webserver is going to send.
Send the actual data in the 'body'
With flask:
Forcing application/json MIME type in a view (Flask)
http://flask.pocoo.org/docs/0.10/patterns/streaming/
def get(self):
try:
os.stat(BACKUP_PATH)
except:
os.mkdir(BACKUP_PATH)
now = datetime.now() # current date and time
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
time = now.strftime("%H:%M:%S")
date_time = now.strftime("%d_%m_%Y_%H:%M:%S")
TODAYBACKUPPATH = BACKUP_PATH + '/' + date_time
try:
os.stat(TODAYBACKUPPATH)
except:
os.mkdir(TODAYBACKUPPATH)
print ("checking for databases names file.")
if os.path.exists(DB_NAME):
file1 = open(DB_NAME)
multi = 1
print ("Databases file found...")
print ("Starting backup of all dbs listed in file " + DB_NAME)
else:
print ("Databases file not found...")
print ("Starting backup of database " + DB_NAME)
multi = 0
if multi:
in_file = open(DB_NAME,"r")
flength = len(in_file.readlines())
in_file.close()
p = 1
dbfile = open(DB_NAME,"r")
while p <= flength:
db = dbfile.readline() # reading database name from file
db = db[:-1] # deletes extra line
dumpcmd = "mysqldump -h " + DB_HOST + " -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
os.system(dumpcmd)
gzipcmd = "gzip " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
os.system(gzipcmd)
p = p + 1
dbfile.close()
else:
db = DB_NAME
dumpcmd = "mysqldump -h " + DB_HOST + " -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
os.system(dumpcmd)
gzipcmd = "gzip " + pipes.quote(TODAYBACKUPPATH) + "/" + db + ".sql"
os.system(gzipcmd)
# t = ("Your backups have been created in '" + TODAYBACKUPPATH + "' directory")
return "Your Folder have been created in '" + TODAYBACKUPPATH + "'."
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.