例如目标机器的IP是 192.168.1.100, 用户名abc , 密码333
怎么通过代码登录并且获取返回值user:?
例如目标机器的IP是 192.168.1.100, 用户名abc , 密码333
怎么通过代码登录并且获取返回值user:?
关注C++语言默认库中不支持telnet操作,如果想要使用则可以通过boost库来实现,或者使用Windows提供的套接字接口自己实现该功能,例如有如下这样的一段代码;
void telnet(const char* host, const char* port)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo* result = NULL, * ptr = NULL, hints;
int iResult;
char recvbuf[512];
int recvbuflen = 512;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0)
{
std::cerr << "WSAStartup failed with error: " << iResult << std::endl;
return;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo(host, port, &hints, &result);
if (iResult != 0)
{
std::cerr << "getaddrinfo failed with error: " << iResult << std::endl;
WSACleanup();
return;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
std::cerr << "socket failed with error: " << WSAGetLastError() << std::endl;
WSACleanup();
return;
}
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET)
{
std::cerr << "Unable to connect to server!" << std::endl;
WSACleanup();
return;
}
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
{
std::cout.write(recvbuf, iResult);
std::cout.flush();
std::string message;
std::getline(std::cin, message);
message += "\n";
iResult = send(ConnectSocket, message.c_str(), (int)message.length(), 0);
if (iResult == SOCKET_ERROR)
{
std::cerr << "send failed with error: " << WSAGetLastError() << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return;
}
} else if (iResult == 0)
std::cout << "Connection closed\n";
else
std::cerr << "recv failed with error: " << WSAGetLastError() << std::endl;
} while (iResult > 0);
closesocket(ConnectSocket);
WSACleanup();
}
你只需要传入两个参数,IP地址和端口字符串,就可以实现telnet访问目标主机的功能。