Running simple script in background
@kaan191, good to hear you are having fun! I have been a bit quiet here lately, which just means I have a ”hot Pythonista project” on that takes up most of my time.
See below for the script I used to communicate with my Pi. I have it configured in Pythonista actions in three different modes:
- Move this file to Pi
- Move this directory to Pi
- Run this file on Pi – move the file, run it, and show the output in Pythonista.
#coding: utf-8
import paramiko
import editor, console
import os.path
import sys
console.clear()
local_path = editor.get_path()
remote_path = os.path.basename(local_path)
local_dir_path = os.path.dirname(local_path)
remote_dir_path = local_dir_path.split('/')[-1]
print('Open SSH connection')
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(<local IP address>, 22, username=<username>, password=<password>, timeout=4)
sftp = s.open_sftp()
fixed_local_root = None
fixed_remote_root = <target dir under root on Pi>
try:
sftp.mkdir(fixed_remote_root)
except:
pass # Ok if already exists
if sys.argv[1] == 'dir':
print('--- Send directory')
#sftp.put(local_dir_path, remote_dir_path)
#parent = os.path.split(local_dir_path)[1]
prefix_len = len(local_dir_path)
for walker in os.walk(local_dir_path):
remote_sftp_path = remote_dir_path + walker[0][prefix_len:]
if remote_sftp_path.endswith('/'):
remote_sftp_path = remote_sftp_path[:-1]
try:
pass
#sftp.mkdir(os.path.join(remotepath, walker[0]))
except:
pass
for file in walker[2]:
print('put', os.path.join(walker[0],file), remote_sftp_path + '/' + file)
#sftp.put(os.path.join(walker[0],file),os.path.join(remotepath,walker[0],file))
else:
print('--- Send file')
sftp.put(local_path, remote_path)
if sys.argv[1] == 'run':
print('--- Run it')
stdin, stdout, stderr = s.exec_command('python3 ' + remote_path)
for line in stdout.readlines():
print(line.rstrip('\n'))
s.close()
print('--- Done')
for line in stderr.readlines():
print('ERROR:', line.rstrip('\n'))
print('--- Complete')
Python SMB Connection
@cvp said:
from ftplib import FTP import paramiko
ftplib for FTP
paramiko for SFTP
There is also FTPS is that better for security?
how can i use this with Ports ?
from ftplib import FTP_TLS
ftp = FTP_TLS()
ftp.ssl_version = ssl.PROTOCOL_SSLv23
ftp.ssl_version = ssl.PROTOCOL_TLSv1_2
ftp.debugging = 2
ftp.connect('localhost', 2121)
ftp.login('developer', 'password')
return ftp
but which version TLS or SSL ?
Python SMB Connection
@cvp said:
from ftplib import FTP import paramiko
ftplib for FTP
paramiko for SFTP
I know I'm annoying you a lot, but would you have a script like with SMB?
Python SMB Connection
from ftplib import FTP
import paramiko
ftplib for FTP
paramiko for SFTP
Need to take a One Drive file and upload it to a FTP
@cvp done
I think is the function sftp, the server is a plain FTP...
Exception: Error reading SSH protocol banner
Traceback (most recent call last):
File "/var/containers/Bundle/Application/E5EADB2F-39AA-4401-9C74-050227C872BA/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/paramiko/transport.py", line 1855, in _check_banner
buf = self.packetizer.readline(timeout)
File "/var/containers/Bundle/Application/E5EADB2F-39AA-4401-9C74-050227C872BA/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/paramiko/packet.py", line 327, in readline
buf += self._read_timeout(timeout)
File "/var/containers/Bundle/Application/E5EADB2F-39AA-4401-9C74-050227C872BA/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/paramiko/packet.py", line 497, in _read_timeout
raise socket.timeout()
socket.timeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/var/containers/Bundle/Application/E5EADB2F-39AA-4401-9C74-050227C872BA/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/paramiko/transport.py", line 1711, in run
self._check_banner()
File "/var/containers/Bundle/Application/E5EADB2F-39AA-4401-9C74-050227C872BA/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/paramiko/transport.py", line 1859, in _check_banner
raise SSHException('Error reading SSH protocol banner' + str(e))
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
Error reading SSH protocol banner
Thanks.
Need to take a One Drive file and upload it to a FTP
@Tito including SFTP
import base64
import os
import paramiko
import requests
import sys
# https://towardsdatascience.com/how-to-get-onedrive-direct-download-link-ecb52a62fee4
def create_onedrive_directdownload (onedrive_link):
data_bytes64 = base64.b64encode(bytes(onedrive_link, 'utf-8'))
data_bytes64_String = data_bytes64.decode('utf-8').replace('/','_').replace('+','-').rstrip("=")
resultUrl = f"https://api.onedrive.com/v1.0/shares/u!{data_bytes64_String}/root/content"
return resultUrl
def main():
path = sys.argv[0]
i = path.rfind('/')
path = path[:i+1]
ip = 'my ip'
user = 'user'
pwd = 'password'
try:
sftp_port = 22
transport = paramiko.Transport((ip, sftp_port))
transport.connect(username=user, password=pwd)
sftp = paramiko.SFTPClient.from_transport(transport)
files = {'a.py':'https://1drv.ms/u/s!AnAqP7kYeMWrgX9L-9sMT08F', 'aa.txt':'https://1drv.ms/t/s!AnAqP7kYeMWrggCb2Umu3Wn_'}
for nam_file in files:
url_file = create_onedrive_directdownload(files[nam_file])
r = requests.get(url_file)
with open(nam_file, mode='wb') as fil:
fil.write(r.content)
sftp.put(path + nam_file, nam_file)
os.remove(nam_file)
sftp.close()
transport.close()
except Exception as e:
print(str(e))
if __name__ == '__main__':
main()
SCP to remote server
@ihf try this, not tested
import paramiko
import appex
import os
hostname = 'xxxxx'
password = 'yyyyy'
source = appex.get_images()
dest = 'xxx'
username = "zzzzz"
port = 22
try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
path = 'temp.jpg'
i = 0
for im in source:
im.save(path, quality=95)
a = sftp.put(path, dest+str(i)+'.jpg')
os.remove(path)
i += 1
finally:
t.close()
Edit: tested and corrected
Please, in the future, insert our code between two lines of triple back-quotes
SCP to remote server
I would like to use the Share sheet to send a photo to a remote server. The following script is my attempt but clearly my use of appex.get_image is wrong but it also fails with appex.get_filepath. How do I properly specify the file from the sharesheet for the sftp.put? I'd also like it to work if I select multiple photos.
import appex
hostname = 'ipaddress'
password = 'password'
source = appex.get_image()
dest = 'destfilepath'
username = "username"
port = 22
try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
a = sftp.put(source, dest)
finally:
t.close()
Installing the scp module via pip (in stash)
@FarmerPaco, if it helps, this is not exactly scp, but does the same thing:
#coding: utf-8
import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("<ip>", port, username='...', password='...', timeout=4)
sftp = s.open_sftp()
sftp.mkdir(remote_dir) # if needed
sftp.put(local_path, remote_path)
s.close()