A former National Security Agency contractor described as a “hoarder” by his lawyer pleaded guilty Thursday to illegally retaining a huge volume of government secrets at his house in what investigators initially suspected could be a major espionage case.

Harold T. Martin III, 54, was arrested in 2016 and detained after the FBI found that he had taken reams of sensitive files, including six full bankers boxes and 50 terabytes of data, to his home over a period of two decades.

At the time of his arrest at his home in Glen Burnie, Md., authorities feared the worst — that Martin may have been a witting or unwitting conduit of sensitive NSA hacking tools to rival nations.

For months, FBI agents tried unsuccessfully to get him to explain what he had done and whether he had shared the information, according to people familiar with the case.

On Thursday, he pleaded guilty to one count of willful retention of national defense information.

“After an exhaustive government investigation, it is clear that Mr. Martin had no intention to harm his country or the intelligence agencies he served,” said his lawyer James Wyda. “His actions were the product of mental illness, not treason. . . . He is deeply remorseful. He is a veteran and a patriot. He has devoted his life to his faith, his family and his country. Now, Mr. Martin is focused on taking care of his health and making amends as best he can.”

John C. Demers, assistant attorney general for national security, said Martin was entrusted “with some of the nation’s most sensitive classified secrets” and has “admitted to violating that trust and putting our nation’s security at risk.”

Under the terms of his plea agreement, Martin acknowledged that, starting in the late 1990s, when he worked as a contractor for different agencies and held a security clearance that gave him access to extremely sensitive classified information, he stole and retained documents marked as top secret.

He admitted that he kept that material, both on paper and in digital form, at his home and in his car.

The plea agreement struck with prosecutors calls for a nine-year sentence, although a judge will decide how much prison time Martin ultimately serves. He is scheduled to be sentenced in July.

The case marked another embarrassing chapter for the NSA, which faced renewed questions about its ability to detect workers who were stealing highly sensitive material.