Why would a professor agree to write recommendation letter, then mention in it that he doesn't know student very well?
In many cases professors agree to write letters for students we do not know well because we are the best option, according to the student, for them. Some students do not have good enough relationships with enough professors to get all the letters of reference they need. They may approach a professor and say, "I know we do not know each other very well and I only took a class with you/worked in your lab for two weeks/etc, but I need someone else to write a letter and I think you are in the best option I have". At which point, the professor may agree. If the student is not as up front, hopefully, the professor was clear and said something like "I don't know you very well, but I can write you a letter and talk about X." Again, some students will agree.

While it is not desirable to have references from people who do not know you well, including in a reference that you do not know the person well is not inherently bad. In fact, it probably is better to be up front about the relationship because it explains why the letter is so narrowly focused.