avatarMike Wolfe

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4551

Abstract

span class="hljs-keyword">for</span> <span class="hljs-keyword">line</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">file</span>: <span class="hljs-keyword">print</span>(<span class="hljs-keyword">line</span>)</pre></div><div id="c36f"><pre><span class="hljs-built_in">file</span>.<span class="hljs-built_in">close</span>() client.<span class="hljs-built_in">close</span>()</pre></div><figure id="d98f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*WhJfmlmbQd98Xk3t0Bt4Dw.png"><figcaption>The output of the text file.</figcaption></figure><h1 id="62e3">Sending a File For Fun</h1><p id="f855">While reading the <a href="https://docs.paramiko.org/en/stable/api/sftp.html">SFTP documentation</a>, I noticed that there was a function to send a file to a remote destination. Since being able to read a remote file went pretty easily, I decided to give this <i>put</i> function a shot. Going off what was already in my <i>remote_operations</i> class, I added a new function that when copies a file to the given remote destination.</p><blockquote id="84fe"><p>Note: The put function is only for copying local files to a remote server.</p></blockquote><div id="d775"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">send_file</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, ssh_client, filename, destination</span>): sftp_client = ssh_client.open_sftp() sftp_client.put(filename, destination) <span class="hljs-keyword">return</span> sftp_client</pre></div><p id="5db2">Just like when reading a file, it was necessary to check if the new <i>send_file</i> function will actually work. Using the already created test file, I made a call to the new function.</p><div id="b148"><pre><span class="hljs-keyword">test </span>= remote_operations()</pre></div><div id="e605"><pre><span class="hljs-attr">client</span> = test.connect(<span class="hljs-string">"HOSTNAME"</span>, <span class="hljs-string">"USERNAME"</span>, <span class="hljs-string">"PASSWORD"</span>)</pre></div><div id="c07c"><pre><span class="hljs-attr">send</span> = test.send_file(client, <span class="hljs-string">"test2.txt"</span>, <span class="hljs-string">"/destination/test2.txt"</span>)</pre></div><div id="4991"><pre><span class="hljs-built_in">send</span>.<span class="hljs-built_in">close</span>() client.<span class="hljs-built_in">close</span>()</pre></div><figure id="6f88"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lU0iJwau22ZdiYnwUsRdAg.png"><figcaption>Local file copied to a remote server.</figcaption></figure><h1 id="539b">Other Goodies</h1><p id="c546">Outside of reading files and sending them to remote locations, the Paramikos SFTP client has many more functions that can be used for managing files. I won’t go into great detail about them here, but some notable ones are:</p><ul><li>listdir — list all items in a specified directory</li><li>mkdir — create a new directory at a specified path</li><li>remove — removes a specified file (only works for files)</li><li>rmdir — removes the given directory</li><li>rename — changes the name of a file or directory</li></ul><p id="e67d">Feel free to play around with these and see what you can get them to do!</p><h1 id="8cd7">Conclusion</h1><p id="d0ce">To say that Paramiko is an awesome package is a clear understatement. Its many features are easy to use and can help you get something up and running very quickly. In all honesty, I was under the impression that working with remote files was going to be a programming nightmare. Fortunately, I was proven wrong by how easy it is to use Paramikos functions. Let me know in the comments how you manage remote files and if you prefer a different Python package. Until next time, cheers!</p><p id="5ba6"><b><i>Read all my articles for free with my <a href="https://crafty-leader-2062.ck.page/8f8bcfb181">weekly newsletter</a>, thanks!</i></b></p><p id="e272"><b><i>Want to read all articles on Medium? Become a Medium <a href="https://miketechgame.medium.com/membership">member</a> today!</i></b></p><p id="4c62">Check out some of my recent articles:</p><div id="f3bc" class="link-block"> <a href="https://towardsdatascience.com/all-about-big-data-ae01afacc081"> <div> <div> <h2>All About Big Data</h2> <div><h3>A deeper dive into what big data is and how it is stored</h3></div> <div><p>towardsdatascience.com</p></div> </div>

Options

          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*_0X_T440jfo2__rr)"></div>
          </div>
        </div>
      </a>
    </div><div id="4ded" class="link-block">
      <a href="https://python.plainenglish.io/i-suck-at-coding-cb9bc7ef6c06">
        <div>
          <div>
            <h2>I Suck At Coding</h2>
            <div><h3>Using Pylint to review my code…</h3></div>
            <div><p>python.plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*dLTi22htUleDWBCfWr2JmQ.jpeg)"></div>
          </div>
        </div>
      </a>
    </div><div id="fc3d" class="link-block">
      <a href="https://python.plainenglish.io/arrays-vs-list-vs-dictionaries-47058fa19d4e">
        <div>
          <div>
            <h2>Arrays vs List vs Dictionaries in Python</h2>
            <div><h3>Comparing the different data storage types in Python</h3></div>
            <div><p>python.plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*42dMysmpbqM60Wd4)"></div>
          </div>
        </div>
      </a>
    </div><div id="77bd" class="link-block">
      <a href="https://python.plainenglish.io/converting-a-cli-app-to-typer-6c7462f5a9ff">
        <div>
          <div>
            <h2>Converting a CLI App To Typer</h2>
            <div><h3>How hard could it be?</h3></div>
            <div><p>python.plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*_4-wjkRUNld6yhpk)"></div>
          </div>
        </div>
      </a>
    </div><div id="fe6a" class="link-block">
      <a href="https://towardsdatascience.com/commonly-used-words-in-data-science-ea06a8f17577">
        <div>
          <div>
            <h2>Commonly Used Words In Data Science</h2>
            <div><h3>Defining the Data Science buzz words</h3></div>
            <div><p>towardsdatascience.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*JA0zEe8XF6-jT4-Q)"></div>
          </div>
        </div>
      </a>
    </div><p id="5bce">References:</p><div id="2ed7" class="link-block">
      <a href="https://www.paramiko.org/index.html">
        <div>
          <div>
            <h2>Paramiko</h2>
            <div><h3>Paramiko is a Python (2.7, 3.4+) implementation of the SSHv2 protocol [1], providing both client and server…</h3></div>
            <div><p>www.paramiko.org</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div>
          </div>
        </div>
      </a>
    </div><h2 id="3fe4">Further Reading</h2><div id="a0a9" class="link-block">
      <a href="https://plainenglish.io/blog/improve-remote-development-workflow-with-fewer-tools-single-context">
        <div>
          <div>
            <h2>Improve Remote Development Workflow with Fewer Tools, Single Context</h2>
            <div><h3>It's fair to say that working remotely is no longer "the future of work". It's the current standard for many tech…</h3></div>
            <div><p>plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*WbRPfev1KQgyyPzf)"></div>
          </div>
        </div>
      </a>
    </div><p id="b2c2"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>. Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a><i>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b>YouTube</b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b>Discord</b></a>. Interested in Growth Hacking? Check out <a href="https://circuit.ooo/"><b>Circuit</b></a>.</i></p></article></body>

Something I Learned This Week — Paramiko’s Remote File Management

Another Python package to the rescue…

Photo by Adam Birkett on Unsplash

A couple of days ago, I was busy at my whiteboard going over the design of a new Python application that would be used to read files on my NAS (Network Attached Storage). Since it’s a fairly simple app, there was only one question that was really bugging me. How do I get Python to read a file on a remote server? Little did I know that the answer was already in front of me. On multiple past projects, I have used a package called Paramiko. According to the package website, Paramiko is a Python implementation of the SSH (Secure Shell) protocol. If you do what I did and don’t read the documentation, you’ll also discover that it can be an SFTP (Simple File Transfer Protocol) client as well. With this newfound information, I figured that Paramiko would once again answer my question. But I needed to test it first.

Reading a Remote File

Eager to see if Paramiko will save the day once more, I created a new file called remote_operations.py.

touch remote_operations.py

Once the new Python file was created, I opened it, imported Paramiko, and declared a new class:

import paramiko
class remote_operations:
     def __init__(self):
          pass

After that, I wrote a function that starts a new SSH connection:

def connect(self, hostname, username, password):
     client = paramiko.SSHClient()
     client.load_system_host_keys()
     client.connect(hostname, username=username, password=password)
     return client

The next function I wrote will start an SFTP client and open the passed file:

def open_remote_file(self, ssh_client, filename):
     sftp_client = ssh_client.open_sftp()
     file = sftp_client.open(filename)
     return file

Essentially, the open_remote_file function is the meat and potatoes of what I needed for my application to work properly. The last step to do before claiming success is to test these new functions. In order to do so, I created another file called test.py and imported the new remote_operations class within it.

from remote_operations import remote_operations

Next, I declared a new instance of the remote_operations class, called the connect function to open a new SSH session, and called the open_remote_file function.

test = remote_operations()
client = test.connect("HOSTNAME", "USERNAME", "PASSWORD")
file = test.open_remote_file(client, "/filepath/test.txt")

Lastly, I wrote some test code to loop through the lines in the file and closed the SFTP client and SSH session.

for line in file:
     print(line)
file.close()
client.close()
The output of the text file.

Sending a File For Fun

While reading the SFTP documentation, I noticed that there was a function to send a file to a remote destination. Since being able to read a remote file went pretty easily, I decided to give this put function a shot. Going off what was already in my remote_operations class, I added a new function that when copies a file to the given remote destination.

Note: The put function is only for copying local files to a remote server.

def send_file(self, ssh_client, filename, destination):
     sftp_client = ssh_client.open_sftp()
     sftp_client.put(filename, destination)
     return sftp_client

Just like when reading a file, it was necessary to check if the new send_file function will actually work. Using the already created test file, I made a call to the new function.

test = remote_operations()
client = test.connect("HOSTNAME", "USERNAME", "PASSWORD")
send = test.send_file(client, "test2.txt", "/destination/test2.txt")
send.close()
client.close()
Local file copied to a remote server.

Other Goodies

Outside of reading files and sending them to remote locations, the Paramikos SFTP client has many more functions that can be used for managing files. I won’t go into great detail about them here, but some notable ones are:

  • listdir — list all items in a specified directory
  • mkdir — create a new directory at a specified path
  • remove — removes a specified file (only works for files)
  • rmdir — removes the given directory
  • rename — changes the name of a file or directory

Feel free to play around with these and see what you can get them to do!

Conclusion

To say that Paramiko is an awesome package is a clear understatement. Its many features are easy to use and can help you get something up and running very quickly. In all honesty, I was under the impression that working with remote files was going to be a programming nightmare. Fortunately, I was proven wrong by how easy it is to use Paramikos functions. Let me know in the comments how you manage remote files and if you prefer a different Python package. Until next time, cheers!

Read all my articles for free with my weekly newsletter, thanks!

Want to read all articles on Medium? Become a Medium member today!

Check out some of my recent articles:

References:

Further Reading

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.

Python
Programming
Automation
Paramiko
Software Development
Recommended from ReadMedium