Code Monkey home page Code Monkey logo

react-native-ssh-sftp's Introduction

react-native-ssh-sftp

SSH and SFTP client library for React Native.

Installation

npm install react-native-ssh-sftp --save
react-native link react-native-ssh-sftp

iOS (only)

NMSSH is required for iOS.

  1. Initialize Pod:
    cd ios
    pod init
    
  2. Open Podfile and add:
    target '[your project's name]' do
    	pod 'NMSSH', '2.2.8'
    end
    
  3. Install Pod:
    pod install
    

Manual Link

iOS

  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project's name]
  2. Go to node_modulesreact-native-ssh-sftp and add RNSSHClient.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libRNSSHClient.a to your project's Build PhasesLink Binary With Libraries

Android

  1. Open up android/app/src/main/java/[...]/MainActivity.java - Add import com.reactlibrary.RNSshClientPackage; to the imports at the top of the file - Add new RNSshClientPackage() to the list returned by the getPackages() method
  2. Append the following lines to android/settings.gradle:
    include ':react-native-ssh-sftp'
    project(':react-native-ssh-sftp').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-ssh-sftp/android')
    
  3. Insert the following lines inside the dependencies block in android/app/build.gradle:
    compile project(':react-native-ssh-sftp')
    

Demo

example

  • This library is also used in iOS app PiHelper.




Run demo

iOS

cd example
cd ios
pod install
cd ..
npm install
react-native run-ios

Android

cd example
npm install
react-native run-android

Usage

Create a client using password authentication

import SSHClient from 'react-native-ssh-sftp';

let client = new SSHClient('10.0.0.10', 22, 'user', 'password', (error) => {
  if (error)
    console.warn(error);
});

Create a client using public key authentication

import SSHClient from 'react-native-ssh-sftp';

let client = new SSHClient('10.0.0.10', 22, 'user', {privateKey: '-----BEGIN RSA......'}, (error) => {
  if (error)
    console.warn(error);
});
  • Public key authentication also supports:
{privateKey: '-----BEGIN RSA......'}
{privateKey: '-----BEGIN RSA......', publicKey: 'ssh-rsa AAAAB3NzaC1yc2EA......'}
{privateKey: '-----BEGIN RSA......', publicKey: 'ssh-rsa AAAAB3NzaC1yc2EA......', passphrase: 'Password'}

Close client

client.disconnect();

Execute SSH command

var command = 'ls -l';
client.execute(command, (error, output) => {
  if (error)
    console.warn(error);
  if (output)
    console.warn(output);
});

Shell

Start shell:

  • Supported ptyType: vanilla, vt100, vt102, vt220, ansi, xterm
var ptyType = 'vanilla';
client.startShell(ptyType, (error) => {
  if (error)
    console.warn(error);
});

Read from shell:

client.on('Shell', (event) => {
  if (event)
    console.warn(event);
});

Write to shell:

var str = 'ls -l\n';
client.writeToShell(str, (error) => {
  if (error) 
    console.warn(error);
});

Close shell:

client.closeShell();

SFTP

Connect SFTP

client.connectSFTP((error) => {
  if (error)
    console.warn(error);
});

List directory:

var path = '.';
client.sftpLs(path, (error, response) => {
  if (error)
    console.warn(error);
  if (response)
    console.warn(response);
});

Create directory:

client.sftpMkdir('dirName', (error) => {
  if (error)
    console.warn(error);
});

Rename file or directory:

client.sftpRename('oldName', 'newName', (error) => {
  if (error)
    console.warn(error);
});

Remove directory:

client.sftpRmdir('dirName', (error) => {
  if (error)
    console.warn(error);
});

Remove file:

client.sftpRm('fileName', (error) => {
  if (error)
    console.warn(error);
});

Download file:

client.sftpDownload('[path-to-remote-file]', '[path-to-local-direcotry]', (error, downloadedFilePath) => {
  if (error)
    console.warn(error);
  if (downloadedFilePath)
    console.warn(downloadedFilePath);
});

// Downlowd progress
client.on('DownloadProgress', (event) => {
  console.warn(event);
});

// Cancel download:
client.sftpCancelDownload();

Upload file:

client.sftpUpload('[path-to-local-file]', '[path-to-remote-directory]', (error) => {
  if (error)
    console.warn(error);
});

// Upload progress
client.on('UploadProgress', (event) => {
  console.warn(event);
});

// Cancel upload:
client.sftpCancelUpload();

Close SFTP:

client.disconnectSFTP();

Credits

  • iOS SSH library: NMSSH
  • Android SSH library: JSch

react-native-ssh-sftp's People

Contributors

ben305 avatar limaofeng avatar shaqian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-ssh-sftp's Issues

Invalid privatekey: [B@c7e5e5a

Hii,

I followed the example code but when I replace it with my RSA key it is always throwing an Invalid private key. My RSA key starting with ---BEGIN RSA PRIVATE KEY--- and ends with ---END RSA PRIVATE KEY. How to resolve this issue? please help me out on this.

And can we load the PPK file directly in the key section, not by string text?

Regards,
Nagavikas

BundleRelease .apk file error with buildToolsVersion = "28.0.3"

`> Task :react-native-ssh-sftp:verifyReleaseResources FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-ssh-sftp:verifyReleaseResources'.

1 exception was raised by workers:
com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
/Users/a/Documents/project/CameraControl/node_modules/react-native-ssh-sftp/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:7: error: resource android:attr/colorError not found.
/Users/a/Documents/project/CameraControl/node_modules/react-native-ssh-sftp/android/build/intermediates/res/merged/release/values-v26/values-v26.xml:11: error: resource android:attr/colorError not found.
....`

Anyone can help me.

NMSSHSession init error

Hey. Thanks for putting this library together.

Earlier, I tried to install it, using the Pod instructions; and encountered an error. It was on the line:

_session = [[NMSSHSession alloc] init];

It seems the most recent version of NMSSH doesn't allow the init function to be called. I got around this error by downgrading to the version of NMSSH I saw the example was using. I'm not too familiar with how Podfiles work, but I was wondering if there was a way to set an upper limit for the version of a pod.

If it's possible, I'm happy to submit a PR with the change.

Not working

Now working from last release react-native !!

Unable to connect to server

I am having some issue with connection to the SFTP server. This is the log i am getting currently.

NMSSH: Socket connection to _serveraddress_ on port 22 succesful
Connection to host _serveraddress_ failed

but after looking further into the issue I found the the following issue

Unable to negotiate with ... port **: no matching host key type found. Their offer: ssh-rsa,ssh-dss
Looks like the library in the app is asking for a key negotiation that the server doesn't support.

This is what the server is offering

HostKeyAlgorithms

         Specifies the host key signature algorithms that the server offers.  The default for this option is:
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            ssh-ed25519,
            ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,
            [[email protected]](mailto:[email protected]),
            [[email protected]](mailto:[email protected]),
            rsa-sha2-512,rsa-sha2-256
         The list of available signature algorithms may also be obtained using "ssh -Q HostKeyAlgorithms".

The reason is because of this

https://security.stackexchange.com/questions/226131/openssh-declares-ssh-rsa-deprecated-what-do-i-do-next

is it possible to get the library to use a more secure host key type?
Guess options are:

  • use rsa-sha2-256 on client
  • use ssh-ed25519 on client

Any help would be greatly appreciated.

Thanks

Error: I try to build for release with this packages

Task :react-native-ssh-sftp:verifyReleaseResources FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-ssh-sftp:verifyReleaseResources'.

java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
error: resource android:style/TextAppearance.Material.Widget.Button.Borderless.Colored not found.
error: resource android:style/TextAppearance.Material.Widget.Button.Colored not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:7: error: resource android:attr/colorError not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:11: error: resource android:attr/colorError not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values-v26\values-v26.xml:15: error: style attribute 'android:attr/keyboardNavigationCluster' not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2711: error: resource android:attr/fontStyle not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2712: error: resource android:attr/font not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2713: error: resource android:attr/fontWeight not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2714: error: resource android:attr/fontVariationSettings not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2715: error: resource android:attr/ttcIndex not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2796: error: resource android:attr/startX not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2799: error: resource android:attr/startY not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2802: error: resource android:attr/endX not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2805: error: resource android:attr/endY not found.
D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\node_modules\react-native-ssh-sftp\android\build\intermediates\res\merged\release\values\values.xml:2813: error: resource android:attr/offset not found.
error: failed linking references.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 1m 52s
237 actionable tasks: 3 executed, 234 up-to-date
PS D:\vaxel\Documents\Feedbook\test\feedbook-mobile-react\android>

App keeps crashing

I am on Android version 9 on S8+. I cloned the rep and ran it on my device but the app keeps crashing.

I have noticed this first on my application where trying to run any functions after initialization of SSHClient keeps crashing the app. Thinking I have done something wrong I tried the example but that also keeps crashing.

Tried debugging with the remote debugger but no luck. Please help. Thanks

Uploading multiple files failed.

This works well for uploading one file, but uploading multiple files in a loop, many warnings occur and no files are uploaded.
Failed to upload /storage/emulated/0/Pictures/images/image-cc78bb9a-6024-4361-9cdb-fcc9248be864.jpg
console.warn @ C:\Users\nvbay\Demo1…Box\YellowBox.js:67
(anonymous) @ C:\Users\nvbay\Demo1…ns\ImageGrid.js:221
(anonymous) @ C:\Users\nvbay\Demo1…h-sftp\index.js:131
__invokeCallback @ C:\Users\nvbay\Demo1…MessageQueue.js:414
(anonymous) @ C:\Users\nvbay\Demo1…MessageQueue.js:127
__guard @ C:\Users\nvbay\Demo1…MessageQueue.js:314
invokeCallbackAndReturnFlushedQueue @ C:\Users\nvbay\Demo1…MessageQueue.js:126
(anonymous) @ debuggerWorker.js:80
My code:

    var i;
    for (i = 0; i < this.state.selected.length; i++) {
      var fileName = this.state.selected[i].uri.toString();
      // remove 'file://' of fileName
      fileName = fileName.substring(7, fileName.length);
      this.sendFile(fileName);
    }
sendFile(fileName) {
    console.log(fileName);
    let { sftpClient } = this.state;
    sftpClient.sftpUpload(fileName, '', (error) => {
    if (error)
        console.warn(error);
    });

    // Upload progress
    sftpClient.on('UploadProgress', (event) => {
      console.warn(event);
    });

    // Cancel upload:
    sftpClient.sftpCancelUpload();
  }

Do you have any solutions to help me?
Thanks in advance!

Pod install erro

HI. I am using React Native 0.63.2 and trying to implement your library. When I reached to Pod install path I got this error. Can you have a look into it. Thanks

`
[!] The 'Pods-vhomes_v2' target has libraries with conflicting names: libssl.a and libcrypto.a.
- Check to see if there is an updated version that contains the necessary podspec file
- Contact the library maintainers or send them a PR to add a podspec. The react-native-webview podspec is a good example of a package.json driven podspec. See
https://github.com/react-native-community/react-native-webview/blob/master/react-native-webview.podspec
- If necessary, you can disable autolinking for the dependency and link it manually. See
https://github.com/react-native-community/cli/blob/master/docs/autolinking.md#how-can-i-disable-autolinking-for-unsupported-library

Aborting run
An unexpected error was encountered. Please report it as a bug:
Error:
[!] use_native_modules! skipped the react-native dependency 'react-native-ssh-sftp'. No podspec file was found.

at CocoaPodsPackageManager._installAsync (/Users/creative/.npm/_npx/43767/lib/node_modules/pod-install/build/index.js:2:81979)
at process._tickCallback (internal/process/next_tick.js:68:7)

`

App crash when trying to close shell

hi,

I am using react-native-ssh-sftp as an ssh shell. It works fine. But when I try to close the ssh shell, my app crash.
I get the below logs from adb logcat command.

RNSSHClient: Error starting shell: Stream closed
AndroidRuntime: FATAL EXCEPTION: Thread-19
AndroidRuntime: Process: com.remotefilemanager, PID: 10904
AndroidRuntime: java.lang.RuntimeException: Illegal callback invocation from native module. This callback type only permits a single invocation from native code.
AndroidRuntime: 	at com.facebook.react.bridge.CallbackImpl.invoke(CallbackImpl.java:25)
AndroidRuntime: 	at com.reactlibrary.RNSshClientModule$3.run(RNSshClientModule.java:200)
AndroidRuntime: 	at java.lang.Thread.run(Thread.java:919)
ActivityTaskManager:   Force finishing activity com.remotefilemanager/.MainActivity

It seems that the callback of startShell invoked more than one time. first when the shell started correctly and then when I closed the shell and got the error in reading from the stream(BufferedReader).

Please help me to fix this problem.

my testing enviroment information:

  • platform: android 10 (emulator)
  • react: "16.9.0"
  • react-native: "0.61.5"
  • react-native-ssh-sftp: "^1.0.3",

npm-version out of date

Hi shaquian,

thanks for the lib, I just noticed that the current npm-version is behind master in the GitHub-repo.

发现npm上的版本落后master分支,希望可以更新一下。

  • ReactNative version: 0.62.2

可以修改package.json的dependencies,在0.6x的RN中使用最新版本。

{
   "react-native-ssh-sftp": "git://github.com/shaqian/react-native-ssh-sftp.git"
}

之后按照以下步骤就可以顺利在ios与andorid端使用这个库了;

  1. yarn install;
  2. cd ios;
  3. pod install;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.