Trying to copy files from a remote desktop to my local.
Here is the code that tried...
import os
import os.path
import shutil
import sys
import win32wnet
def netcopy(host, source, dest_dir, username=None, password=None, move=False):
""" Copies files or directories to a remote computer. """
wnet_connect(host, username, password)
dest_dir = covert_unc(host, dest_dir)
# Pad a backslash to the destination directory if not provided.
if not dest_dir[len(dest_dir) - 1] == '\\':
dest_dir = ''.join([dest_dir, '\\'])
# Create the destination dir if its not there.
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
else:
# Create a directory anyway if file exists so as to raise an error.
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
if move:
shutil.move(source, dest_dir)
else:
shutil.copy(source, dest_dir)
Trying to figure out how to establish a connection and copy files over to my local.
New to python here...
Are you using an RDP client?
Is this windows linux or mac ?
Which app are you using?
Is this a code you wrote ?
Do you know what virtual channels are ?
Is NLA on?
THere is very little information you provided.
can you even connect ? Can you ping the server ?
Related
I just put my hand on a OpenMV Cam H7 Plus that is using micro-python. I am trying an example that is supposed to take a python program to ask for a picture from the camera and save it. As far as I understand (still new to python) is the camera IDE creates a virtual serial port and listens for a command. The main python program try to open the port (COM4) and is denied. The problem , I think, is the port is already in use. How can I get access?
IDE micro-python code
import sensor, image, time, ustruct
from pyb import USB_VCP
usb = USB_VCP()
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 2000) # Wait for settings take effect.
print("USB is a Com Port", usb.isconnected())
while(True):
cmd = usb.recv(4, timeout=5000)
if (cmd == b'snap'):
img = sensor.snapshot().compress()
usb.send(ustruct.pack("<L", img.size()))
usb.send(img)
Main python Code
import serial
import struct
port = 'COM4'
sp = serial.Serial(port, baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
xonxoff=False, rtscts=False, stopbits=serial.STOPBITS_ONE, timeout=None, dsrdtr=True)
sp.setDTR(True) # dsrdtr is ignored on Windows.
sp.write("snap")
sp.flush()
size = struct.unpack('<L', sp.read(4))[0]
img = sp.read(size)
sp.close()
with open("img.jpg", "w") as f:
f.write(img)
And in running the main i get the error:
File "C:\Users\Vincent\usbpcvtest\lib\site-packages\serial\serialwin32.py", line 62, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)
I find out how it works. The Cam auto-run the main.py when you initialize the port with a program on another computer. So all i had to do is renamed my IDE micro-python code "main.py" and to put it in the root of the cam.
the only bug is if you start the IDE you need to reconnect the cam physicaly so that the cam boot the main.py before you start your program on the main computer.
Using Apache airflow tool, how can I implement a DAG for the following Python code. The task accomplished in the code is to get a directory from GPU server to local system. Code is working fine in Jupyter notebook. Please help to implement in Airflow...I'm very new to this. Thanks.
import pysftp
import os
myHostname = "hostname"
myUsername = "username"
myPassword = "pwd"
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
print("Connection successfully stablished ... ")
src = '/path/src/'
dst = '/home/path/path/destination'
os.mkdir(dst)
sftp.get_d(src, dst, preserve_mtime=True)
print("Fetched source images from GPU server to local directory")
# connection closed automatically at the end of the with-block```
For SFTP duties, Airflow provides SFTOperator that you can use directly.
Alternatively it's corresponding SFTPHook can be used with a simple PythonOperator
I acknowledge there aren't many examples, but this might be helpful
For SSH-connection, see this
This question already has answers here:
Directory transfers with Paramiko
(13 answers)
Recursive directory copy with Paramiko in Python
(5 answers)
Closed 2 years ago.
I am new to Python 3, I have a question here.., Using Python libraries/modules like Paramiko
I was able to login into SFTP Server successfully. I want to copy / upload a file from Local server directory to specified SFTP server directory.
I was able to do it successfuly for one particular file, i.e., I was able to copy / upload a particular file from Local path to SFTP server path.
But , my question is how do I copy / upload all files in a particular Local directory to target SFTP server directory , in one go ?
Which Python library / module is good d for this task ?
Below is the code which I have developed :
So here in the below python code, I could upload only a single file from local path to the SFTP target path successfully ,
but how do I upload all files in a particular local path to the desired SFTP target path ? I need to do this in one go.
import paramiko
import os
SFTP_Server_Host = axdjuorjdf#ujt.com
SFTP_UserName = fbhipy
SFTP_Password = xxxxxxxxx
sftp_ssh = paramiko.SSHClient()
sftp_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp_ssh.connect(hostname=SFTP_Server_Host ,username=SFTP_UserName ,password=SFTP_Password)
sftp_check = sftp_ssh.open_sftp()
print("Connected to SFTP server : " +SFTP_Server_Host)
print()
print("Username of SFTP server : " +SFTP_UserName)
print()
sftp_check.chdir('dev/sample/user/test_data')
sftp_check.mkdir('app_data')
sftp_check.put('C:\\Prod_data\\Sample_prod.csv','dev/sample/user/test_data/app_data/Sample_prod.csv')
print("File transfered to SFTP Server : " +SFTP_Server_Host)
print()
--> Here instead of mentioning a particular file name , how could I upload all files from 'C:\Prod_data\' to 'dev/sample/user/test_data/app_data/'? <--
I'm trying to install packages in Atom editor, but it always fails, just like if I coudn't get a connexion to the server.
For instance, apm install split-diff returns Request for package information failed: getaddrinfo ENOTFOUND atom.io atom.io:443 (ENOTFOUND)
I'm running Atom 1.32.2 on Linux Mint 19.
I don't use a proxy.
Check your DNS servers.
I ran into this problem randomly this afternoon when initially everything was working on my Mac.
I can reach the Internet fine. Github is up and reporting no issues, Atom.io is up...
Clues re:etc/hosts from other comments here pointed me to my my network settings anyway.
Checked and I have my DNS servers configured for VPN access, once I added OpenDNS servers as well, Atom installs starting working again.
Finally, I found out where the bug was!
For some reasons of personal convenience, I replaced /etc/hosts with a symlink (towards some place in my ~/ folder). THIS is what apm didn't like. (No idea why. I'd be glad to know...) Switching back to a real file for /etc/hosts made me able to install packages again.
I just installed split-diff and it loaded fine. Open Atom and under the Atom menu item select Preferences. This opens a new window and on the left side of the pane is a row of actions starting with Core and followed by Editor, URI Handling, and 5 other actions. Click on the Install action. This is where you can find and install extensions. Once you clicked on Install, the pane changes and there is a search box at the top. In the search box type split-diff and the name of your extension should appear. There should be a blue install button for the script. Click install and it should work.
I am on Ubuntu 16.04 and I was having this problem. I had a directory called /etc/hosts/ which was a cloned version of this repo.
Clearly having a directory named the same as a file isn't exactly a smart move, but I was able to solve the problem through moving the directory and running the install script for the repo again. The install script calls a which flushes the DNS file, found in line 1193 of this file here.
I extracted the script/function which should do the trick;
#!/usr/bin/env python3
# Script by Ben Limmer
# https://github.com/l1m5
#
# This Python script will combine all the host files you provide
# as sources into one, unique host file to keep you internet browsing happy.
import argparse
import fnmatch
import json
import locale
import os
import platform
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from glob import glob
import lxml # noqa: F401
from bs4 import BeautifulSoup
# Detecting Python 3 for version-dependent implementations
PY3 = sys.version_info >= (3, 0)
if PY3:
from urllib.request import urlopen
else:
raise Exception("We do not support Python 2 anymore.")
# Syntactic sugar for "sudo" command in UNIX / Linux
if platform.system() == "OpenBSD":
SUDO = ["/usr/bin/doas"]
else:
SUDO = ["/usr/bin/env", "sudo"]
# Project Settings
BASEDIR_PATH = os.path.dirname(os.path.realpath(__file__))
def flush_dns_cache():
"""
Flush the DNS cache.
"""
print("Flushing the DNS cache to utilize new hosts file...")
print(
"Flushing the DNS cache requires administrative privileges. You might need to enter your password."
)
dns_cache_found = False
if platform.system() == "Darwin":
if subprocess.call(SUDO + ["killall", "-HUP", "mDNSResponder"]):
print_failure("Flushing the DNS cache failed.")
elif os.name == "nt":
print("Automatically flushing the DNS cache is not yet supported.")
print(
"Please copy and paste the command 'ipconfig /flushdns' in "
"administrator command prompt after running this script."
)
else:
nscd_prefixes = ["/etc", "/etc/rc.d"]
nscd_msg = "Flushing the DNS cache by restarting nscd {result}"
for nscd_prefix in nscd_prefixes:
nscd_cache = nscd_prefix + "/init.d/nscd"
if os.path.isfile(nscd_cache):
dns_cache_found = True
if subprocess.call(SUDO + [nscd_cache, "restart"]):
print_failure(nscd_msg.format(result="failed"))
else:
print_success(nscd_msg.format(result="succeeded"))
centos_file = "/etc/init.d/network"
centos_msg = "Flushing the DNS cache by restarting network {result}"
if os.path.isfile(centos_file):
if subprocess.call(SUDO + [centos_file, "restart"]):
print_failure(centos_msg.format(result="failed"))
else:
print_success(centos_msg.format(result="succeeded"))
system_prefixes = ["/usr", ""]
service_types = ["NetworkManager", "wicd", "dnsmasq", "networking"]
for system_prefix in system_prefixes:
systemctl = system_prefix + "/bin/systemctl"
system_dir = system_prefix + "/lib/systemd/system"
for service_type in service_types:
service = service_type + ".service"
service_file = path_join_robust(system_dir, service)
service_msg = (
"Flushing the DNS cache by restarting " + service + " {result}"
)
if os.path.isfile(service_file):
dns_cache_found = True
if subprocess.call(SUDO + [systemctl, "restart", service]):
print_failure(service_msg.format(result="failed"))
else:
print_success(service_msg.format(result="succeeded"))
dns_clean_file = "/etc/init.d/dns-clean"
dns_clean_msg = "Flushing the DNS cache via dns-clean executable {result}"
if os.path.isfile(dns_clean_file):
dns_cache_found = True
if subprocess.call(SUDO + [dns_clean_file, "start"]):
print_failure(dns_clean_msg.format(result="failed"))
else:
print_success(dns_clean_msg.format(result="succeeded"))
if not dns_cache_found:
print_failure("Unable to determine DNS management tool.")
You need to use a filter breaker. I had the same problem installing the file_icons package, and the package was installed when the Siphon filter breaker was connected.
I have created the below script and saved it as (test.mr) in the lib folder and running from the command prompt C:\Android_Stuff\android-sdk-windows\tools\lib\monkeyrunner test.mr
#Importing monkeyrunner
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
#waiting for the device connection
device = MonkeyRunner.waitForConnection()
#Installing my app.
device.installPackage('C:/Android_Stuff/android-sdk-windows/tools/lib/purchase.apk')
#starting my demo page
device.startActivity(component='com.mobilemoneynetwork.purchase/.demo')
#selecting the Menu Button.
device.press('KEYCODE_MENU','DOWN_AND_UP')
I am getting
Unable to access jarfile ..\framework\archquery.jar
SWT folder '' does not exist.
Please set ANDROID_SWT to point to the folder containing swt.jar for your platform.
Set ANDROID_SWT path in environment variable it should be "your path"\Android\Sdk\tools\lib\x86_64