Leverage environment variables within SFTP paths when using Paramiko

Currently, I am executing a script on my server and attempting to retrieve some files from my Firewall. However, when I use an environment variable (signified by the $ symbol) to reference the file, I encounter a "file not found" error. Surprisingly, I have no issues accessing the file when I input a standard path. It's worth noting that the code may appear messy; this is just for demonstration purposes. Below is the functional snippet:

_savedLocation = "/home/kartal/Desktop/aaa.tgz"
folder, savedLocation = os.path.split(_savedLocation)
remotepath = "$FWDIR/bin/upgrade_tools/"
remotefile = remotepath + savedLocation
stdin, stdout, stderr =
  ssh.exec_command("cd {} && yes | ./migrate export {} ".format(remotepath, savedLocation))
time.sleep(120)
command = "cd {} && chmod 777 {}".format(remotepath, savedLocation)
stdin, stdout, stderr = ssh.exec_command(command)
sftp = ssh.open_sftp()
sftp.get(remotefile, _savedLocation)
sftp.close()
ssh.close()

If I substitute the

remotepath = "/opt/r80/fw1/bin/upgrade_tools/"
, the code runs smoothly.

Furthermore, during the initial step, I execute the "migrate" script with $FWDIR. Consequently, $FWDIR functions correctly with exec_command, but encounters issues with SFTP get.

What could be the root of the problem, and how can I rectify it?

Answer №1

When working with SFTP, it's important to note that environment variables cannot be used. Instead, real paths must be utilized directly. For example, the real path in this case would be /opt/CPsuite-R80/fw1.

If you do need to obtain the real path from a variable value that is not fixed, you will have to resolve the variable using a different interface, such as shell access. This is similar to what you would do in WinSCP by executing the command cd $FWDIR in the shell. The shell then resolves $FWDIR to /opt/CPsuite-R80/fw1. In Paramiko, you can accomplish a similar task using SSHClient.exec_command:

stdin, stdout, stderr = ssh.exec_command("echo $FWDIR")
fwdir = stdin.read()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to enhance specific sections of Django content by incorporating <span> tags, while maintaining the original paragraph text format?

I am currently in the process of trying to showcase a paragraph of text (content) from django. However, my aim is to incorporate <span class="modify"> into particular words that match pre-defined words located within a referenceList within the paragr ...

Truth Values and their Roles in Functions

I'm struggling with creating a function in Python that takes three boolean values and returns true if at least two are true. The function seems to work fine when I call it explicitly in the interpreter after running the program: >>> function ...

Attempting to utilize Selenium code in order to continuously refresh a webpage until a button becomes clickable

After receiving valuable assistance from the online community, I managed to create a script that can navigate through a webpage and join a waitlist. The issue arises when the 'join waitlist' button is not clickable because the waitlist is not ope ...

Combining multiple dictionaries of dictionaries in Python by adding up their values to create a unified dictionary

How can I combine the dictionaries within a dictionary, excluding the main keys, and aggregating the values of similar keys across dictionaries? Input: {'first':{'a': 5}, 'second':{'a': 10}, 'third':{&apo ...

Determine the upload date of all channel videos using yt_dlp

Is it possible to extract the upload date in a json for all videos of a channel? I am looking to get a json output that includes the upload dates of all videos. Here is the code I have: import json import yt_dlp as youtube_dl options = {'ignoreerrors ...

Is there a way to combine three separate lines of information in the output into one cohesive format?

My goal is to display two lines of code together rather than as separate entities. The desired output includes Twitter usernames and the number of retweets they have made, using an excel sheet filled with data and incorporating the xlrl module. for cell ...

Ways to interact with elements lacking an identifier

Currently, I'm faced with an HTML challenge where I need to interact with an element labeled tasks. *<td class="class_popup2_menuitem_caption" unselectable="on" nowrap="">Tasks</td>* In my attempt to do so, I've implemented the foll ...

Unpacking Key-Value Pairs in Python

I am developing a software program where I have a dictionary that contains only one key and one value. My goal is to assign the key to a variable named 'key' and the value to a variable named 'value.' Here is the relevant code snippet: ...

Transmit a lexicon containing values encapsulated within a roster to an AJAX solicitation, endeavoring to dissect it at the receiving

My goal is to send a dictionary that looks like this (values in a list): datax = { "name": ["bhanu", "sivanagulu","daniel"], "department": ["HR", "IT", "FI"]} In ...

Exploring the depths of dictionaries within pyarrow

Recently, I've been experimenting with pyarrow and encountered some challenges when attempting to convert nested dictionaries into Tables. Take a look at the code snippet below: import pyarrow as pa a = {'a':{'b':[1,2,3], 'c& ...

Uploading a file to FastAPI server with CURL: Step-by-step guide

I am in the process of configuring a FastAPI server that is capable of accepting a single file upload from the command line through the use of curl. To guide me, I am following the FastAPI Tutorial located at: from typing import List from fastapi import ...

Guide to retrieving multiple book search results through the Google Books API

Currently, I am utilizing the Google Books API to retrieve search results with multiple books. Below is my implementation: def lookup(search): """Look up search for books.""" # Contact API try: url = f&apos ...

What is the best way to locate a web element in Selenium using Python when it does not have an ID

I'm having trouble selecting an element on the minehut.com webpage that doesn't have an ID. Despite trying CSS Selectors, I haven't had any success. The element I want to select is: <button _ngcontent-c17 color="Primary" mat-raised-bu ...

What is the best way to determine the correct xpath to locate and access all profiles on a webpage utilizing Selenium and Python?

As a beginner in the world of programming, I have embarked on an exciting journey to create a test software for automating data retrieval from a website. Despite my enthusiasm, I am encountering challenges in defining the xpath that would allow me to locat ...

Developing a personalized address field in Django Model

What is the standard method for storing postal addresses in Django models? Are there any specialized libraries available that offer custom model fields with built-in validation and formatting for postal address data? If no libraries are found, how can I c ...

Challenges with arrays while using a for loop

I'm trying to transform an array A with 10 elements into an array B with 100 elements. Each element in B ranging from 0 to 9 should be the same as element 0 in A Each element in B ranging from 10 to 19 should be the same as element 1 in A .... Eac ...

I'm just starting out with Python and I'm wondering how I can access the initial values for precipitation, temperature, wind gust, and humidity

from selenium import webdriver import time PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get("https://www.metoffice.gov.uk/weather/forecast/gcvwr3zrw#?date=2020-07-12") time.sleep(5 ...

Which CMS is better for creating a social network: Drupal or WordPress?

Creating a community for web-comic artists to synchronize their websites is my current project. The dilemma I am facing now is deciding between using Drupal or Wordpress as the CMS. Although Drupal is renowned for its Social Networking capabilities, I fo ...

Utilize the Euler technique with Python

I am attempting to use Euler's method in Python to compute a sequence of numbers, but I am encountering overflow errors due to the large value of N (10000000). Does anyone have any suggestions for a more efficient way to perform this calculation? def ...

Obtain variances between two sets of dictionaries (presented as two distinct lists of differences)

Update: I am seeking a solution that is compatible with lists of dictionaries (which are not hashable), making this query unique as it differs from the question on Compute list difference I possess two lists of dictionaries, each comprising gmail labels/f ...