Socket网络编程--FTP客户端
0.环境安装
环境使用我的这一篇文章安装好libssh2库。
http://www.cnblogs.com/wunaozai/p/4528394.html
使用一个带有SFTP功能的FTP服务器。注意有些FTP服务器是不带SFTP功能的。这里我使用这个FreeSSHd作为SFTP服务器。
http://www.freesshd.com/?ctt=download
关于freesshd配置说两句,Server status标签 点击确定SSH server is running。SSH标签,确定配置完成。Authentication标签下Password authentication为Allowed,Public key authentication为Disabled,这样做的原因是我接下来要做的程序只支持密码登录,减少不必要的干扰,如果有需要,可以自己设定。Tunneling标签,所有选项选中,如果没有选中,本地如果网络复杂的话,可能会有问题。SFTP标签,选择一个作为FTP的根目录。Users标签,增加一个用户。基本设置就这些了。
1.示例讲解
我们先从libssh2中的示例程序进行讲解,libssh2源代码中的example文件夹中有几个常见的示例程序,我们此次先讲解上传文件和下载文件这两个基础功能。
下面这个是sftp_write_nonblock.c的源代码,已被折叠。
下面这个是sftp_nonblock.c的源代码
上面一个是发送文件到sftp服务器,下面是从sftp服务器获取文件。编译和运行结果如下图所示。
2.修改示例程序
软件提供的源代码是比较完整的,为了方便,对里面的功能进行修改。修改为符合本次使用的windows版本,仅支持密码访问。
sftp-write.c 用于把本地文件上传到sftp服务器中
sftp-read.c 用于把服务器上的文件下载到本地中
至于用到的libssh2_config.h这个文件,没有的话可以在代码中注释掉.
下面这个是freesshd产生的日志中一部分
1 05-28-2015 14:18:05 HOST localhost SSH connection attempt. 2 05-28-2015 14:18:05 HOST localhost SSH user successfully logged on using password. 3 05-28-2015 14:18:06 SFTP service granted to user user. 4 05-28-2015 14:18:06 HOST localhost user is uploading wunaozai.txt (E:\wunaozai.txt) 5 05-28-2015 14:18:06 HOST localhost SSH user disconnected. 6 05-28-2015 14:18:23 HOST localhost SSH connection attempt. 7 05-28-2015 14:18:23 HOST localhost SSH user successfully logged on using password. 8 05-28-2015 14:18:23 SFTP service granted to user user. 9 05-28-2015 14:18:23 HOST localhost user is uploading wunaozai.txt (E:\wunaozai.txt) 10 05-28-2015 14:18:23 HOST localhost SSH user disconnected. 11 05-28-2015 14:18:49 HOST localhost SSH connection attempt. 12 05-28-2015 14:18:49 HOST localhost SSH user successfully logged on using password. 13 05-28-2015 14:18:49 SFTP service granted to user user. 14 05-28-2015 14:18:49 HOST localhost user is uploading wunaozai.txt (E:\wunaozai.txt) 15 05-28-2015 14:18:49 HOST localhost SSH user disconnected. 16 05-28-2015 14:18:55 HOST localhost SSH connection attempt. 17 05-28-2015 14:18:56 HOST localhost SSH user successfully logged on using password. 18 05-28-2015 14:18:56 SFTP service granted to user user. 19 05-28-2015 14:18:56 HOST localhost user is downloading wunaozai.txt (E:\wunaozai.txt) 20 05-28-2015 14:18:56 HOST localhost SSH user disconnected.
有了上面这两个主要的功能,SFTP的客户端就基本功能实现了,至于mkdir和dir功能就参考里面的示例程序,基本都可以看懂。
3.使用putty连接freesshd
了解过SFTP原理之后,就知道,SFTP其实跟FTP没有多大的关系,其实就是一个使用SSH协议,然后进行会话,会话过程保存为文件,嗯,大概就是这个样子了。所以我们可以使用普通的ssh软件进行登录,拿到该SFTP服务器站点的SHELL。然后可以各种操作,看起来很危险的样子,所以不管用什么SFTP服务器在配置用户的时候要注意的。 putty工具里面还有个PSFTP.exe这个工具可以连接到SFTP服务器,没事的也可以玩玩看。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30264814/viewspace-1676177/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/30264814/viewspace-1676177/