PageRenderTime 39ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/SharpSSH-1.1.1.12RC4.src/jsch/examples/Sftp.cs

http://sshsync.googlecode.com/
C# | 474 lines | 430 code | 25 blank | 19 comment | 90 complexity | c5b11fb70f2762889d5ff972a7f9e2a4 MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Windows.Forms;
  5. /* ScpTo.cs
  6. * ====================================================================
  7. * The following example was posted with the original JSch java library,
  8. * and is translated to C# to show the usage of SharpSSH JSch API
  9. * ====================================================================
  10. * */
  11. namespace Tamir.SharpSsh.jsch.examples
  12. {
  13. /// <summary>
  14. /// This program will demonstrate the sftp protocol support.
  15. /// You will be asked username, host and passwd.
  16. /// If everything works fine, you will get a prompt 'sftp>'.
  17. /// 'help' command will show available command.
  18. /// In current implementation, the destination path for 'get' and 'put'
  19. /// commands must be a file, not a directory.
  20. /// </summary>
  21. public class Sftp
  22. {
  23. public static void Main(String[] arg)
  24. {
  25. try
  26. {
  27. JSch jsch=new JSch();
  28. InputForm inForm = new InputForm();
  29. inForm.Text = "Enter username@hostname";
  30. inForm.textBox1.Text = Environment.UserName+"@localhost";
  31. if (!inForm.PromptForInput())
  32. {
  33. Console.WriteLine("Cancelled");
  34. return;
  35. }
  36. String host = inForm.textBox1.Text;
  37. String user=host.Substring(0, host.IndexOf('@'));
  38. host=host.Substring(host.IndexOf('@')+1);
  39. Session session=jsch.getSession(user, host, 22);
  40. // username and password will be given via UserInfo interface.
  41. UserInfo ui=new MyUserInfo();
  42. session.setUserInfo(ui);
  43. session.connect();
  44. Channel channel=session.openChannel("sftp");
  45. channel.connect();
  46. ChannelSftp c=(ChannelSftp)channel;
  47. Stream ins=Console.OpenStandardInput();
  48. TextWriter outs=Console.Out;
  49. ArrayList cmds=new ArrayList();
  50. byte[] buf=new byte[1024];
  51. int i;
  52. String str;
  53. int level=0;
  54. while(true)
  55. {
  56. outs.Write("sftp> ");
  57. cmds.Clear();
  58. i=ins.Read(buf, 0, 1024);
  59. if(i<=0)break;
  60. i--;
  61. if(i>0 && buf[i-1]==0x0d)i--;
  62. //str=Util.getString(buf, 0, i);
  63. //Console.WriteLine("|"+str+"|");
  64. int s=0;
  65. for(int ii=0; ii<i; ii++)
  66. {
  67. if(buf[ii]==' ')
  68. {
  69. if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); }
  70. while(ii<i){if(buf[ii]!=' ')break; ii++;}
  71. s=ii;
  72. }
  73. }
  74. if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); }
  75. if(cmds.Count==0)continue;
  76. String cmd=(String)cmds[0];
  77. if(cmd.Equals("quit"))
  78. {
  79. c.quit();
  80. break;
  81. }
  82. if(cmd.Equals("exit"))
  83. {
  84. c.exit();
  85. break;
  86. }
  87. if(cmd.Equals("rekey"))
  88. {
  89. session.rekey();
  90. continue;
  91. }
  92. if(cmd.Equals("compression"))
  93. {
  94. if(cmds.Count<2)
  95. {
  96. outs.WriteLine("compression level: "+level);
  97. continue;
  98. }
  99. try
  100. {
  101. level=int.Parse((String)cmds[1]);
  102. Hashtable config=new Hashtable();
  103. if(level==0)
  104. {
  105. config.Add("compression.s2c", "none");
  106. config.Add("compression.c2s", "none");
  107. }
  108. else
  109. {
  110. config.Add("compression.s2c", "zlib,none");
  111. config.Add("compression.c2s", "zlib,none");
  112. }
  113. session.setConfig(config);
  114. }
  115. catch{}//(Exception e){}
  116. continue;
  117. }
  118. if(cmd.Equals("cd") || cmd.Equals("lcd"))
  119. {
  120. if(cmds.Count<2) continue;
  121. String path=(String)cmds[1];
  122. try
  123. {
  124. if(cmd.Equals("cd")) c.cd(path);
  125. else c.lcd(path);
  126. }
  127. catch(SftpException e)
  128. {
  129. Console.WriteLine(e.message);
  130. }
  131. continue;
  132. }
  133. if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
  134. {
  135. if(cmds.Count<2) continue;
  136. String path=(String)cmds[1];
  137. try
  138. {
  139. if(cmd.Equals("rm")) c.rm(path);
  140. else if(cmd.Equals("rmdir")) c.rmdir(path);
  141. else c.mkdir(path);
  142. }
  143. catch(SftpException e)
  144. {
  145. Console.WriteLine(e.message);
  146. }
  147. continue;
  148. }
  149. if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
  150. {
  151. if(cmds.Count!=3) continue;
  152. String path=(String)cmds[2];
  153. int foo=0;
  154. if(cmd.Equals("chmod"))
  155. {
  156. byte[] bar=Util.getBytes((String)cmds[1]);
  157. int k;
  158. for(int j=0; j<bar.Length; j++)
  159. {
  160. k=bar[j];
  161. if(k<'0'||k>'7'){foo=-1; break;}
  162. foo<<=3;
  163. foo|=(k-'0');
  164. }
  165. if(foo==-1)continue;
  166. }
  167. else
  168. {
  169. try{foo=int.Parse((String)cmds[1]);}
  170. catch{}//(Exception e){continue;}
  171. }
  172. try
  173. {
  174. if(cmd.Equals("chgrp")){ c.chgrp(foo, path); }
  175. else if(cmd.Equals("chown")){ c.chown(foo, path); }
  176. else if(cmd.Equals("chmod")){ c.chmod(foo, path); }
  177. }
  178. catch(SftpException e)
  179. {
  180. Console.WriteLine(e.message);
  181. }
  182. continue;
  183. }
  184. if(cmd.Equals("pwd") || cmd.Equals("lpwd"))
  185. {
  186. str=(cmd.Equals("pwd")?"Remote":"Local");
  187. str+=" working directory: ";
  188. if(cmd.Equals("pwd")) str+=c.pwd();
  189. else str+=c.lpwd();
  190. outs.WriteLine(str);
  191. continue;
  192. }
  193. if(cmd.Equals("ls") || cmd.Equals("dir"))
  194. {
  195. String path=".";
  196. if(cmds.Count==2) path=(String)cmds[1];
  197. try
  198. {
  199. ArrayList vv=c.ls(path);
  200. if(vv!=null)
  201. {
  202. for(int ii=0; ii<vv.Count; ii++)
  203. {
  204. object obj = vv[ii];
  205. if(obj is ChannelSftp.LsEntry)
  206. outs.WriteLine(vv[ii]);
  207. }
  208. }
  209. }
  210. catch(SftpException e)
  211. {
  212. Console.WriteLine(e.message);
  213. }
  214. continue;
  215. }
  216. if(cmd.Equals("lls") || cmd.Equals("ldir"))
  217. {
  218. String path=".";
  219. if(cmds.Count==2) path=(String)cmds[1];
  220. try
  221. {
  222. //java.io.File file=new java.io.File(path);
  223. if(!File.Exists(path))
  224. {
  225. outs.WriteLine(path+": No such file or directory");
  226. continue;
  227. }
  228. if(Directory.Exists(path))
  229. {
  230. String[] list=Directory.GetDirectories(path);
  231. for(int ii=0; ii<list.Length; ii++)
  232. {
  233. outs.WriteLine(list[ii]);
  234. }
  235. continue;
  236. }
  237. outs.WriteLine(path);
  238. }
  239. catch(Exception e)
  240. {
  241. Console.WriteLine(e);
  242. }
  243. continue;
  244. }
  245. if(cmd.Equals("get") ||
  246. cmd.Equals("get-resume") || cmd.Equals("get-append") ||
  247. cmd.Equals("put") ||
  248. cmd.Equals("put-resume") || cmd.Equals("put-append")
  249. )
  250. {
  251. if(cmds.Count!=2 && cmds.Count!=3) continue;
  252. String p1=(String)cmds[1];
  253. // String p2=p1;
  254. String p2=".";
  255. if(cmds.Count==3)p2=(String)cmds[2];
  256. try
  257. {
  258. SftpProgressMonitor monitor=new MyProgressMonitor();
  259. if(cmd.StartsWith("get"))
  260. {
  261. int mode=ChannelSftp.OVERWRITE;
  262. if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; }
  263. else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; }
  264. c.get(p1, p2, monitor, mode);
  265. }
  266. else
  267. {
  268. int mode=ChannelSftp.OVERWRITE;
  269. if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; }
  270. else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; }
  271. c.put(p1, p2, monitor, mode);
  272. }
  273. }
  274. catch(SftpException e)
  275. {
  276. Console.WriteLine(e.message);
  277. }
  278. continue;
  279. }
  280. if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
  281. {
  282. if(cmds.Count!=3) continue;
  283. String p1=(String)cmds[1];
  284. String p2=(String)cmds[2];
  285. try
  286. {
  287. if(cmd.Equals("rename")) c.rename(p1, p2);
  288. else c.symlink(p1, p2);
  289. }
  290. catch(SftpException e)
  291. {
  292. Console.WriteLine(e.message);
  293. }
  294. continue;
  295. }
  296. if(cmd.Equals("stat") || cmd.Equals("lstat"))
  297. {
  298. if(cmds.Count!=2) continue;
  299. String p1=(String)cmds[1];
  300. SftpATTRS attrs=null;
  301. try
  302. {
  303. if(cmd.Equals("stat")) attrs=c.stat(p1);
  304. else attrs=c.lstat(p1);
  305. }
  306. catch(SftpException e)
  307. {
  308. Console.WriteLine(e.message);
  309. }
  310. if(attrs!=null)
  311. {
  312. outs.WriteLine(attrs);
  313. }
  314. else
  315. {
  316. }
  317. continue;
  318. }
  319. if(cmd.Equals("version"))
  320. {
  321. outs.WriteLine("SFTP protocol version "+c.version());
  322. continue;
  323. }
  324. if(cmd.Equals("help") || cmd.Equals("?"))
  325. {
  326. outs.WriteLine(help);
  327. continue;
  328. }
  329. outs.WriteLine("unimplemented command: "+cmd);
  330. }
  331. session.disconnect();
  332. }
  333. catch(Exception e)
  334. {
  335. Console.WriteLine(e);
  336. }
  337. }
  338. public class MyUserInfo : UserInfo
  339. {
  340. public String getPassword(){ return passwd; }
  341. public bool promptYesNo(String str)
  342. {
  343. DialogResult returnVal = MessageBox.Show(
  344. str,
  345. "SharpSSH",
  346. MessageBoxButtons.YesNo,
  347. MessageBoxIcon.Warning);
  348. return (returnVal==DialogResult.Yes);
  349. }
  350. String passwd;
  351. InputForm passwordField=new InputForm();
  352. public String getPassphrase(){ return null; }
  353. public bool promptPassphrase(String message){ return true; }
  354. public bool promptPassword(String message)
  355. {
  356. InputForm inForm = new InputForm();
  357. inForm.Text = message;
  358. inForm.PasswordField = true;
  359. if ( inForm.PromptForInput() )
  360. {
  361. passwd=inForm.getText();
  362. return true;
  363. }
  364. else{ return false; }
  365. }
  366. public void showMessage(String message)
  367. {
  368. MessageBox.Show(
  369. message,
  370. "SharpSSH",
  371. MessageBoxButtons.OK,
  372. MessageBoxIcon.Asterisk);
  373. }
  374. }
  375. public class MyProgressMonitor : SftpProgressMonitor
  376. {
  377. private ConsoleProgressBar bar;
  378. private long c = 0;
  379. private long max = 0;
  380. private long percent=-1;
  381. int elapsed=-1;
  382. System.Timers.Timer timer;
  383. public override void init(int op, String src, String dest, long max)
  384. {
  385. bar = new ConsoleProgressBar();
  386. this.max=max;
  387. elapsed=0;
  388. timer=new System.Timers.Timer(1000);
  389. timer.Start();
  390. timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
  391. }
  392. public override bool count(long c)
  393. {
  394. this.c += c;
  395. if(percent>=this.c*100/max){ return true; }
  396. percent=this.c*100/max;
  397. string note = ("Transfering... [Elapsed time: "+elapsed+"]");
  398. bar.Update((int)this.c, (int)max, note);
  399. return true;
  400. }
  401. public override void end()
  402. {
  403. timer.Stop();
  404. timer.Dispose();
  405. string note = ("Done in "+elapsed+" seconds!");
  406. bar.Update((int)this.c, (int)max, note);
  407. bar=null;
  408. }
  409. private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  410. {
  411. this.elapsed++;
  412. }
  413. }
  414. private static String help =
  415. " Available commands:\n"+
  416. " * means unimplemented command.\n"+
  417. "cd path Change remote directory to 'path'\n"+
  418. "lcd path Change local directory to 'path'\n"+
  419. "chgrp grp path Change group of file 'path' to 'grp'\n"+
  420. "chmod mode path Change permissions of file 'path' to 'mode'\n"+
  421. "chown own path Change owner of file 'path' to 'own'\n"+
  422. "help Display this help text\n"+
  423. "get remote-path [local-path] Download file\n"+
  424. "get-resume remote-path [local-path] Resume to download file.\n"+
  425. "get-append remote-path [local-path] Append remote file to local file\n"+
  426. "*lls [ls-options [path]] Display local directory listing\n"+
  427. "ln oldpath newpath Symlink remote file\n"+
  428. "*lmkdir path Create local directory\n"+
  429. "lpwd Print local working directory\n"+
  430. "ls [path] Display remote directory listing\n"+
  431. "*lumask umask Set local umask to 'umask'\n"+
  432. "mkdir path Create remote directory\n"+
  433. "put local-path [remote-path] Upload file\n"+
  434. "put-resume local-path [remote-path] Resume to upload file\n"+
  435. "put-append local-path [remote-path] Append local file to remote file.\n"+
  436. "pwd Display remote working directory\n"+
  437. "stat path Display info about path\n"+
  438. "exit Quit sftp\n"+
  439. "quit Quit sftp\n"+
  440. "rename oldpath newpath Rename remote file\n"+
  441. "rmdir path Remove remote directory\n"+
  442. "rm path Delete remote file\n"+
  443. "symlink oldpath newpath Symlink remote file\n"+
  444. "rekey Key re-exchanging\n"+
  445. "compression level Packet compression will be enabled\n"+
  446. "version Show SFTP version\n"+
  447. "? Synonym for help";
  448. }
  449. }