Skip to content Skip to sidebar Skip to footer

Upload a File to a Server Ssh Powershell

How to Build PowerShell Tools to Setup SFTP

Subscribe banner

When you use multiple machines running Windows, y'all may demand to access shared resource by using different protocols. When a file share is created on a Windows machine, the SMB protocol is usually used. However, files can be shared on non-Windows machines by using NFS, FTP, SFTP, FTPS, SCP, and other protocols. If you're using only PowerShell, for example, on Windows Server without a graphical interface, connecting to the SFTP share for the offset time can seem difficult. This web log post explains how to use SFTP in Windows with PowerShell.

What is SFTP?

SFTP stands for SSH File Transfer Protocol or Secure File Transfer Protocol. SFTP is the secure culling to the traditional File Transfer Protocol (FTP) with similar functionality. SFTP works on the application layer of the OSI model (layer 7), uses the SSH connection, and is specially pop on Linux machines that usually have a born command-line SFTP customer. If you apply Windows, install a free SSH client such as WinSCP, which has a GUI and supports more than but SFTP, or configure PowerShell tools if yous need to use the control line. Windows and PowerShell don't back up SFTP natively, so additional components will need to be installed.

When using an SSH connection, data transfers over the network are encrypted and the connection is secure, different the traditional unencrypted FTP protocol where data can be intercepted by attackers. SSH is used for hallmark, and if you have Linux user credentials, you can admission files on a target Linux auto after passing authentication from your command line SFTP client or a GUI client. Information technology too allows you to copy files from/to a remote Linux machine to your local Linux or Windows machine. Configuring the SFTP server on Linux is not difficult – you install the SSH server, create users, and grant the needed permissions for users and files/directories.

Don't misfile SFTP and FTPS. These 2 protocols are used for similar purposes. All the same, SFTP uses one port number for a connectedness and FTPS uses multiple port numbers for command and data channels (which can be more difficult to configure from a security perspective including firewalls). FTPS is FTP with SSL (Secure Socket Layer). I don't become into how to set upwards SFTP server in this weblog post. Read about installing and configuring Linux (including the SSH server) on Hyper-5 in here.

Installing the Posh-SSH Module

In social club to perform operations with files (copying files, deleting files) on remote machines by using SFTP and SCP in PowerShell, you have to install the Posh-SSH module in PowerShell. Installing this module also allows you to run remote commands on a remote figurer by using the SSH session. PowerShell iii.0 and .NET Framework four.0 are required to install and use Posh-SSH. Thus, you lot tin install this module on Windows 8 or newer Windows versions. You can besides manually update PowerShell and .NET Framework on Windows 7 SP1. Run this control to install the PowerShell SFTP module (Posh-SSH):

install-module posh-ssh

Posh PowerShell – installing the PowerShell SFTP module

As an culling, you can use this control to install the Posh-SSH module for PowerShell:

iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")

An Internet connection is required to install Posh-SSH with the to a higher place commands. In my case, I have installed the Posh-SSH module in PowerShell and can move to the next configuration steps.

Connecting to a Remote Host in PowerShell

In this blog post, I'm using an environment with a local Windows auto and remote Linux car, which are continued to the same network:

  • 192.168.101.210 is a local Windows automobile with Windows 10 version 20H2 installed
  • 192.168.101.209 is a remote Linux machine on which the SSH (SFTP) server is running
  • user1 is the name of the Linux user

These IP addresses are used in my examples. Enter your IP addresses and credentials in the appropriate commands and configuration files.

Let'southward bank check our SFTP share by connecting to the Linux server via SFTP by using WinSCP, the free SFTP client for Windows. Connecting to an SFTP server is straightforward. Enter the IP address of the target host, port number (TCP 22 is the default port number only you can configure an SSH server to use a custom port number), user name, and countersign to connect. Don't forget to select the SFTP protocol.

How to use SFTP – connecting to a remote machine in WinSCP

SFTP connection works in my example. We have copied 2 files to the shared binder (the location of the files is /dwelling/user1/shared/ on the remote Linux auto). Let'due south expect at how to connect to the shared folder from Windows and how to utilise SFTP with Posh-SSH in PowerShell.

How to use SFTP in Windows

To piece of work with files via SFTP, you should institute a session first. In social club to exercise this, run this command in PowerShell:

New-SFTPSession -Computername 192.168.101.209

The authentication window is displayed afterward running the control. Enter a username and password to access the remote Linux machine with the files you need to access via SFTP. If you have entered the correct credentials, yous should see the PowerShell output with the information about the SFTP session number, IP address of the remote host, and connectedness status. One time a session is created, an index number is assigned to the session.

How to use SFTP in PowerShell – connecting to a server and creating a new session

You can always enter the aid control with the appropriate arguments to display the short assist info about the syntax for using PowerShell commands:

help New-SFTPSession

List all available posh PowerShell commands:

Get-Command -Module Posh-SSH

or

Go-command -Name * -module *posh-ssh

Hither is the method to create an SSH session that allows you to run a command on a remote host, for example, to list files in the directory:

Import-Module Posh-SSH

$SSHSession = New-SSHSession -ComputerName 192.168.101.209 -Credential $(Get-Credential) -Verbose

$SSH = $SSHSession | New-SSHShellStream

Invoke-SSHCommand -Index 0 -Command "ls -l /abode/user1/shared"

PowerShell SFTP – listing files in a directory of an SFTP server

Creating a PowerShell Script

Permit's create a test script to explore the basic operations that you lot tin perform in PowerShell when working with SFTP resources. This is non an SFTP script, this is a PowerShell script to piece of work with SFTP. This test script should copy the .Cyberspace Framework installer file from a remote Linux automobile to a local Windows machine.

Create a test-PS.ps1 script file with the content displayed below.

#Creating a binder to store files downloaded from the SFTP share

New-detail -itemtype directory -strength -path c:\temp\ps

#Setting credentials for the user business relationship

$countersign = ConvertTo-SecureString "My_Password000" -AsPlainText -Force

$creds = New-Object Organisation.Direction.Automation.PSCredential ("user1", $countersign)

#Establishing an SFTP session

$Session = New-SFTPSession -Computername 192.168.101.209 -credential $creds

#Downloading the .Internet installer file by using the established SFTP session

Get-SFTPFile -SessionId $session.SessionID -RemoteFile /home/user1/shared/NetFrameworkNDP462.exe -LocalPath c:\temp\ps

Open PowerShell on a Windows machine, go to the binder where this test script is stored, and run the script

.\test-PS.ps1

The NetFrameworkNDP462.exe file should exist copied from /home/user1/shared/ (on a remote Linux automobile) to C:\temp\ps\ (on a local Windows machine). As you can see on the screenshot below, the file is copied successfully in my case.

PowerShell SFTP – copying a file from an SFTP server in PowerShell

In order to list files in a directory in the SFTP resource, you can create a PowerShell script with the following content:

$passwordTest = "Your_Password000"

$securePasswordTest = ConvertTo-SecureString $passwordTest -AsPlainText -Force

$credentialsTest = New-Object System.Management.Automation.PSCredential ("user1", $securePasswordTest)

$sessionTest = New-SFTPSession -ComputerName 192.168.101.209 -Credential $credentialsTest -AcceptKey

$sourceTest = "/dwelling house/user1/shared/"

$destinationTest= "c:\temp\ps\"

Get-SFTPChildItem -Recursive $sessionTest -Path $sourceTest | ForEach-Object{

   if ($_.Fullname -like '*.csv')

   {

      Get-SFTPFile $sessionTest -RemoteFile $_.FullName -LocalPath $destinationTest -Overwrite

   }

   write-output $_.FullName

}

Remove-SFTPSession $sessionTest -Verbose

Where:

Your_Password000 is the password for the user account used to connect via SSH to the SFTP share;

user1 is the name of the user;

192.168.101.209 is the IP accost of the remote host to which we connect to access files via SFTP.

Relieve the script every bit list-files.ps1 and run this script in PowerShell on your local car from a folder where this script file is stored.

.\list-files.ps1

Pay attention to the -Recursive parameter divers in the test script. On the screenshot beneath you can see the results for using the -Recursive parameter and without this parameter.

How to use SFTP in PowerShell – checking contents of a directory on a remote server

Ane of the disadvantages of running scripts such as those shown in the examples higher up is that credentials are stored in the plain text of a script, which is not secure. A user who can open a script (fifty-fifty with read-but permissions) can see a password and use this countersign for unauthorized access.

There is a method to amend the level of security and shop a password in the encrypted view in a file. Windows Data Protection API is used to encrypt a password, which can simply be accessed from the user business relationship and estimator used to create this password file.

(get-credential).countersign | ConvertFrom-SecureString | set-content "C:\temp\countersign.txt"

How to use SFTP in PowerShell – saving an encrypted password to a file

And then the password is saved in the encrypted form in the text file. If somebody sees the content of this file, the password is not displayed as manifestly text.

A password for an SFTP user account is encrypted and saved in the text file

When y'all need to enter the countersign, ascertain the file with a saved encrypted password (C:\temp\password.txt in our case).

$password = Get-Content "C:\temp\password.txt" | ConvertTo-SecureString

$credential = New-Object System.Management.Automation.PsCredential("user1",$password)

This method of defining a password is more than secure. You lot can modify your script in which you defined the password. As an alternative to opening a script in a text editor, you can right-click the ps1 file and in the context card click Edit.

PowerShell SFTP automation – editing a script file

Windows PowerShell ISE is opened. This is a native Windows tool that colorizes syntax for more convenience and displays the available PowerShell commands in the right pane.

SFTP script editing for running in PowerShell

Commands in the exam script are now as follows:

New-item -itemtype directory -force -path c:\temp\ps

$password = Go-Content "C:\temp\password.txt" | ConvertTo-SecureString

$creds = $credential = New-Object Organisation.Management.Automation.PsCredential("user1",$password)

$Session = New-SFTPSession -Computername 192.168.101.209 -credential $creds

Get-SFTPFile -SessionId $session.SessionID -RemoteFile /home/user1/shared/NetFrameworkNDP462.exe -LocalPath c:\temp\ps

You tin modify your script over again and set information technology to execute the downloaded installer file on the Windows car. The command to install .Cyberspace Framework in the quiet mode (from the directory where the installer file is located) is:

.\NetFrameworkNDP462.exe /q /norestart

Enter the name of your installation file if the name is different.

Add the line at the cease of the script:

Start-process "C:\temp\ps\NetFrameworkNDP462.exe" -argumentlist /q /norestart

If you desire to delete the installation file after installation finishes, consider adding this line at the finish of the script:

remove-detail -path "C:\temp\ps\NetFrameworkNDP462.exe" -recurse -force

Using PowerShell and Posh-SSH allows you to automate operations in PowerShell using the SFTP protocol to copy files betwixt hosts in the network. You can create a script for downloading files and executing them to save fourth dimension when yous need to perform mass installation of software on a large number of computers.

Conclusion

This weblog mail service explained how to use SFTP in Windows PowerShell with basic examples and concepts of automating tasks. At present yous tin can copy files to/from Linux machines via SFTP if an SSH server is configured on Linux machines. Posh-SSH is a PowerShell module that is required to utilize SFTP on Windows machines from which yous want to access remote SFTP servers and perform SFTP automation tasks. PowerShell and SFTP can exist used by managed service providers and system administrators in organizations.

PowerShell is oftentimes used to manage Hyper-Five virtual machines and VMware virtual machines (in PowerCLI). Remember to dorsum upwardly your virtual machines. Only equally PowerShell is used to automate running commands, NAKIVO Backup & Replication automates VM backup and provides many additional data protection features. Moreover, the product supports installation in multi-tenant manner, which is especially useful for managed service providers. Download the Free Edition of NAKIVO Backup & Replication and get-go protecting your virtual and physical machines today.

gallagherwasioneating.blogspot.com

Source: https://www.nakivo.com/blog/how-to-build-powershell-tools-to-setup-sftp/

Post a Comment for "Upload a File to a Server Ssh Powershell"